gpt4 book ai didi

c - 当使用 strlen 获取 const char* 的长度时,我得到一个负数?

转载 作者:太空狗 更新时间:2023-10-29 12:20:59 25 4
gpt4 key购买 nike

问题已解决,我在 malloc

时错过了一个 +1

我在 fuse 上做了一些事情,我在这里得到了一个 SIGABRT,然后我使用 gdb 来跟踪它,我发现了一些奇怪的东西。我得到一个负面的 strlen 结果。我想这就是为什么当我 free 我的 char* 时,我得到了这个信号。(sprintf 可能会写入比我们 malloc 更多的字节,所以如果我malloc 一个非常小的数字,它仍然可以写入东西,但是当我释放它时,问题就来了)

函数在这里,参数由fuse(一个使用空间的文件系统)提供。

static int fs_getattr(const char *path, struct stat *stbuf)

{
int res;
char *fullpath = NULL;
fullpath = malloc(cpflen+strlen(path));
sprintf(fullpath, "%s%s", cachepathfix, path);
res = lstat(fullpath, stbuf);
free(fullpath);
}

我运行 gdb 看看那里发生了什么,起初我认为这可能是由于 const char * 没有以 \000 结尾,但实际上以此结束

(gdb) x/10c path
0x8937140: 47 '/' 116 't' 101 'e' 115 's' 116 't' 0 '\000'

然后我尝试 p strlen(path),我得到了一个有线号码 -1218664720

(gdb) p strlen(path)
$2 = -1218664720

是我不能使用 strlen 来测量 const char * 的长度还是我做的其他事情是错误的?谢谢你们。

最佳答案

fullpath 中添加足够的空间来终止空字符。

改变:

fullpath = malloc(cpflen+strlen(path));

到:

fullpath = malloc(sizeof(char) * (cpflen + strlen(path) + 1));

关于c - 当使用 strlen 获取 const char* 的长度时,我得到一个负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8614058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com