【发布时间】: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