【发布时间】:2021-01-04 16:12:26
【问题描述】:
这是我使用 malloc 为 C 中的二维数组分配内存并释放它的代码。 N是用户给的数字
R = malloc(N * sizeof(int *)); // start of memory allocating for **R
if (R == NULL) {
return -1;
}
for (i = 0; i <= N; i++) {
*(R+i) = malloc(N * sizeof(int));
if (*(R + i) == NULL) {
return -1;
}
} // end of memory allocating for **R
for (i = 0 ; i < N; i++){
free(R[i]);
free(R);
}
程序完成后,我得到这个错误:double free or corruption (out) Aborted (core dumped)
通过使用 valgrind 进行调试,我收到以下消息:12 bytes in 1 blocks are definitely lost in loss record 1 of 1
在这行代码中检测到此泄漏(根据 valgrind):*(C+i) = malloc(N * sizeof(int));
关于如何修复它的任何帮助?
【问题讨论】:
-
这段代码不完整。你分配
R,然后你释放C... -
请张贴minimal reproducible example,并在您使用时适当缩进。