【问题标题】:failing to free char pointer memory c未能释放 char 指针内存 c
【发布时间】:2016-08-17 19:19:08
【问题描述】:

我有问题。我正在为char* 分配空间,但是当我尝试free 空间时,我的程序崩溃了。

这是代码

fullPath = (char *) malloc(strlen(path) + strlen(fileData->d_name) + 1);
if (fullPath == NULL)
{
    handleErrors(ERR_ALOCATION_CODE);
}
sprintf(fullPath, "%s/%s", path, fileData->d_name);
//... some more code, I only use fullPath, I don't change it here
free(fullPath);

上面的代码在尝试free 时失败。我将不胜感激。

【问题讨论】:

  • 您还需要为终止的 null 分配内存...
  • 我怀疑您调用的函数之一是存储指向fullPath 内存的指针,并且(未成功)在它被释放后尝试访问它。
  • malloc(strlen(path) + strlen(fileData->d_name) + 1); --> malloc(strlen(path) + 1 /* '/' */ + strlen(fileData->d_name) + 1 /* null */);
  • “为char *分配空间”!

标签: c memory-management free


【解决方案1】:

您没有为终止 NUL 字符的字符串分配空间。所以把分配改成这样:

// allocate memory for 1st part, slash, 2nd part and terminating NUL char
fullPath = malloc(strlen(path) + 1 + strlen(fileData->d_name) + 1);

另请注意,在 C 中,将返回值转换为 malloc 是不好的做法,因此我将其删除。


使用snprintf 可能是一种改进,以防您计算出错误的长度,但在这种情况下可能是一个见仁见智的问题。反正代码就变成了

// size for 1st part, slash, 2nd part and terminating NUL char
size_t bufsize = strlen(path) + 1 + strlen(fileData->d_name) + 1;
fullPath = malloc(bufsize);
//...
snprintf(fullPath, bufsize, "%s/%s", path, fileData->d_name);

那么一个错误不会导致未定义的行为,而是产生从末尾切掉字符的路径。这比随机崩溃要好得多(例如找不到文件错误),更不用说更容易调试了,当您可以打印文件名并查看它是如何不正确时。


一些解释:在问题代码中,因为你分配的1字节太少,导致缓冲区溢出,这是未定义的行为,所以基本上任何事情都可能发生。对于 1 字节缓冲区溢出,很可能不会发生任何坏事,因为在分配结束时 可能 有未使用的字节。所以在某种程度上你真的很幸运能这么早就抓住它。你可以想象找到一个错误有多难,当程序只有在字符串长度是 16 的倍数时才会崩溃,否则就可以工作......幸运的是,有一些工具可以检测这样的东西,但最好的防御是成为一个迂腐的 C 程序员,努力写好代码的人……

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2017-03-01
    • 2016-03-06
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    相关资源
    最近更新 更多