gpt4 book ai didi

c - 让 valgrind 开心 vs 避免段错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:48 24 4
gpt4 key购买 nike

我是 C 的新手,正在尝试学习 char 数组的动态内存分配,但不确定为什么我不能让 valgrind 对 0 错误感到满意,同时避免段错误。我的例子是基于这个例子:

How to dynamically allocate memory for char** in C

根据该示例,我编写了以下测试代码:

#include <stdlib.h>
#include <stdio.h>

int main (int argc, char* argv[]){
char **myChar;

int nEl = 5;
int nChars = 10;

myChar = (char**)malloc(sizeof(char*));
for (int it = 0; it < nEl; it++) {
myChar[it] = (char*)malloc((nChars) * sizeof(char));
}

//for (int it = 0; it < nEl; it++) {
// free(myChar[it]);
//}
//free(myChar);

return 0;
}

它按原样编译,运行没有问题,退出并返回 0x0,但 valgrind 提示:

4 errors in context 1 of 1:
Invalid write of size 8
at 0x400583: main (in /home/username/Documents/personal/tmp/cprog2/test2)
Address 0x5204048 is 0 bytes after a block of size 8 alloc'd
at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
by 0x40054D: main (in /home/username/Documents/personal/tmp/cprog2/test2)

ERROR SUMMARY: 4 errors from 1 contexts (suppressed: 0 from 0)

计算出 valgrind 期望 malloc 的 **myChar 和 myChar[it] 是 free(),我取消注释注释位,但是程序段错误和 valgrind 是这样说的:

4 errors in context 1 of 2:
Invalid read of size 8
at 0x4005EF: main (in /home/username/Documents/personal/tmp/cprog2/test2)
Address 0x5204048 is 0 bytes after a block of size 8 alloc'd
at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
by 0x40058D: main (in /home/username/Documents/personal/tmp/cprog2/test2)


4 errors in context 2 of 2:
Invalid write of size 8
at 0x4005C3: main (in /home/username/Documents/personal/tmp/cprog2/test2)
Address 0x5204048 is 0 bytes after a block of size 8 alloc'd
at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
by 0x40058D: main (in /home/username/Documents/personal/tmp/cprog2/test2)

ERROR SUMMARY: 8 errors from 2 contexts (suppressed: 0 from 0)

为什么我不能让 valgrind 开心并编译和运行一个工作的应用程序?

最佳答案

你没有分配足够的内存:

myChar = (char**)malloc(sizeof(char*));

这为单个 char * 分配了空间,但您将此内存视为分配了 5 个(即 nEl)。

因此,您写入的内存超出了已分配内存的末尾。这就是 Valgrind 在说“地址 0x5204048 在大小为 8 的 block 分配后为 0 字节”时提醒您的内容。这样做会调用未定义的行为,在本例中表现为崩溃。

如果你想为 nEl 指针分配空间,请分配该空间量:

myChar = malloc(sizeof(char*) * nEl);

此外,don't cast the return value of malloc .

关于c - 让 valgrind 开心 vs 避免段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48897471/

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