免费使用问题

Issue using free

我在使用这段代码时遇到问题:

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);
}

代码编译但在 运行 时,程序 returns 出现段错误。我尝试使用 coredump 文件进行调试,但回溯仅显示:

#0  0x00007fb7f7e7e3ac in free () from /lib64/libc.so.6
#1  0x0000000000507739 in main (argc=<optimized out>, argv=<optimized out>) at testprogram.c:460

有线索吗?

你必须使用 strlen 计算两个字符串的长度,而不是 sizeof(它只适用于文字,但无论如何都要避免),但要注意:LOG env。变量可能会丢失,所以在这样做之前针对 NULL 进行测试。

我的提案使用 sprintf,它避免了对 strcatstrcpy 的大量调用,并允许插入 fixed-size 文字,如 /

所以一个相当安全的方法是:

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-terminator 添加了 1 个,为斜线添加了 1 个,只有在执行 sprintf 时我才会包括)

你的 malloc 似乎得到了错误的论据。

getenv 个州的手册页,

The getenv() function returns a pointer to the value in the environment, or NULL if there is no match.

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
}