这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int *mem(void){
//int buf[]= {1,1,2,3};
int *buf = malloc(2 * sizeof(int));
buf[1] = 1;
return buf;
free(buf);
}
int main(void){
int *a[1] = { &mem()[1] };
printf("%d", *a[0]};
free(a[0]);
return 0;
}
正如预期的那样,输出是1,但当我签入Valgrind时,出现了内存泄漏,显示为3个分配和2个释放。我不想在这里使用static
。
有人能帮我解决这个问题吗?
这里应该不太关心内存泄漏。您的程序正在调用未定义的行为,因为您正在释放尚未malloc
d的内存。
将这2行添加到你的程序中,看看程序是怎么回事:
printf("Returning %pn", buf);
return buf;
和
printf("%d at %pn", *a[0], a[0]);
free(a[0]);
输出应该是某种东西:
Returning 0x602000000010
1 at 0x602000000014
在对free
的下一次调用中,传递地址0x602000000014
,其中不是在mem()
中分配的内存。由于我(可能还有您(系统上int
的大小,即&buf[0]
和&buf[1]
相差4个字节,因此free
d的内存与分配的内存之间存在完全4个字节的差异。
将您的程序更改为
int *a[1] = { &mem()[0] }; //point to the 0-th index of the returned buffer
printf("%d", a[0][1]); //get the 1-st index of the array pointed to by the a[0] pointer
要有正确的行为。还有一件事。返回后的语句不会执行。CCD_ 10在CCD_ 11中是冗余的。
编辑:这是在进行更改后运行valgrind后的输出:
$valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose ./test
==3497== HEAP SUMMARY:
==3497== in use at exit: 0 bytes in 0 blocks
==3497== total heap usage: 2 allocs, 2 frees, 520 bytes allocated
==3497==
==3497== All heap blocks were freed -- no leaks are possible
==3497==
==3497== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)