我在这里遇到了这个代码的问题:
int main(int argc, **argv)
{
...
char *dirlog
...
dirlog = malloc(sizeof(getenv("LOG")+strlen("/logfile.log")));
dirlog = strcat(getenv("LOG"),"/logfile.log");
o = strlen(dirlog);
...
free(dirlog);
}
代码编译,但在运行时,程序返回分段错误。我尝试过使用coredump文件进行调试,但是回溯只显示了以下内容:
#0 0x00007fb7f7e7e3ac in free () from /lib64/libc.so.6
#1 0x0000000000507739 in main (argc=<optimized out>, argv=<optimized out>) at testprogram.c:460
有线索吗?
发布于 2018-03-06 17:17:09
您必须使用strlen
来计算这两个字符串的长度,而不是使用sizeof
(它只对文字有效,但无论如何都要避免),但是要小心:LOG
env。变量可能会丢失,因此在执行此操作之前对NULL
进行测试。
我的建议使用sprintf
,它避免了对strcat
和strcpy
的大量调用,并允许插入像/
这样的固定大小的文字。
因此,一种相当安全的方法是:
const char *logroot = getenv("LOG");
if (logroot!=NULL)
{
const char *logfile = "logfile.log";
int len = strlen(logroot)+strlen(logfile)+2; // predict the size of the resulting string
char *dirlog = malloc(len);
sprintf(dirlog,"%s/%s",logroot,logfile);
...
free(dirlog);
}
(我为nul添加了一个,为斜杠添加了一个,只有在执行sprintf
时才会包含)
发布于 2018-03-06 17:19:15
你的malloc
似乎是错误的论点。
getenv
状态手册页,
函数返回指向环境中值的指针,如果没有匹配,则返回NULL。
而strlen("/logfile.log")
将是一个固定的数字。
但是,传递给sizeof
--这是一个字符指针的加法和一个长度的数字--这是没有意义的。
sizeof
不是你所需要的,这是我可以扣减的。
我们可以推理分割错误。对malloc
的调用一定失败了,并且在没有验证的情况下继续进行。
您不需要检查malloc
是否返回任何内容。加上那部分,
char *ptr = getenv("LOG");
size_t sizeRequired = strlen(ptr) + 1 + strlen("logfile.log") + 1;
dirlog = malloc(sizeRequired);
if(dirlog == 0)
{
// Handle the error here and return
}
https://stackoverflow.com/questions/49136390
复制相似问题