被释放的指针未分配(仅限 osx)
下面的函数基本上模拟 mkdir -p
,为给定路径递归创建目录。对于 Linux,我没有任何问题,但是在 OSX 下运行时,在调用 free(dir)
期间,它总是会出现段错误,并出现错误 pointer being freed was not allocate
。任何人都可以发现错误吗?当我在 gdb 中单步执行时,我没有看到任何明显的问题,dir
已填充,并且创建的目录结构没有错误。
static int
mkpath(const char *path)
{
int result = 0;
struct stat st;
char *p = NULL, *dir = strdup(path);
char *tmp = g_malloc0(sizeof(char) * strlen(cache.path) + strlen(dir) + 1);
dir = dirname(dir);
tmp = strcpy(tmp, cache.path);
p = strtok(dir, "/");
while(p != NULL) {
tmp = strncat(tmp, "/", 1);
tmp = strncat(tmp, p, strlen(p));
if(stat(tmp, &st) == 0) {
if(S_ISDIR(st.st_mode)) {
p = strtok(NULL, "/");
continue;
}
result = -ENOTDIR;
break;
}
if(mkdir(tmp, S_IRWXU) == -1) {
result = -errno;
break;
}
p = strtok(NULL, "/");
}
free(tmp);
free(dir);
return result;
}
The function below basically emulates mkdir -p
, recursively creating directories for a given path. With Linux I have no issues, however running under OSX it always segfaults with the error pointer being freed was not allocated
during the call to free(dir)
. Can anyone spot an error? When I step through execution in gdb I don't see any obvious problems, dir
is populated and the directory structure is created without error.
static int
mkpath(const char *path)
{
int result = 0;
struct stat st;
char *p = NULL, *dir = strdup(path);
char *tmp = g_malloc0(sizeof(char) * strlen(cache.path) + strlen(dir) + 1);
dir = dirname(dir);
tmp = strcpy(tmp, cache.path);
p = strtok(dir, "/");
while(p != NULL) {
tmp = strncat(tmp, "/", 1);
tmp = strncat(tmp, p, strlen(p));
if(stat(tmp, &st) == 0) {
if(S_ISDIR(st.st_mode)) {
p = strtok(NULL, "/");
continue;
}
result = -ENOTDIR;
break;
}
if(mkdir(tmp, S_IRWXU) == -1) {
result = -errno;
break;
}
p = strtok(NULL, "/");
}
free(tmp);
free(dir);
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看 dirname 的手册页: http://linux.die.net/man/3 /目录名。 “dirname() 和 basename() 都返回指向以 null 结尾的字符串的指针。(不要将这些指针传递给 free(3)。)”此外,您可能不应该像现在这样执行 dir = dirname(dir)丢失了指向 strdup 分配的内存的指针(strdup 分配的内存应该传递给 free)。
Take a look at the man page for dirname: http://linux.die.net/man/3/dirname. "Both dirname() and basename() return pointers to null-terminated strings. (Do not pass these pointers to free(3).)" Also, you should probably not being doing dir = dirname(dir) as you've then lost the pointer to the memory allocated by strdup (strdup allocated memory should be passed to free).
dirname
的手册页指出,您不应传递将值返回给free()
。但这正是你正在做的事情。The man page for
dirname
says that you should not pass the return value tofree()
. Yet that is exactly what you are doing.根据手册页:
所以你可能不想释放它。我猜Linux上的情况有所不同?
according to the man page:
so you probably don't want to be freeing it. i'm guessing that's different on linux?