当我运行以下代码时,我收到以下内存错误:
Filling an array at address 0x7ff0005c0 with 10 values
Done!
Filling an array at address 0x7ff0005bc with 1 values
Done!
Filling an array at address 0x7ff0005a0 with 4 values
Done!
Filling an array at address 0x4c30040 with 5 values
Done!
Filling an array at address 0x7ff000598 with 16 values
Done!
==30871== Invalid free() / delete / delete[] / realloc()
==30871== at 0x4A07786: free (vg_replace_malloc.c:446)
==30871== by 0x40081A: main (arrays.c:142)
==30871== Address 0x500000002 is not stack'd, malloc'd or (recently) free'd
==30871==
==30871==
==30871== HEAP SUMMARY:
==30871== in use at exit: 16 bytes in 1 blocks
==30871== total heap usage: 2 allocs, 2 frees, 36 bytes allocated
==30871==
==30871== LEAK SUMMARY:
==30871== definitely lost: 16 bytes in 1 blocks
==30871== indirectly lost: 0 bytes in 0 blocks
==30871== possibly lost: 0 bytes in 0 blocks
==30871== still reachable: 0 bytes in 0 blocks
==30871== suppressed: 0 bytes in 0 blocks
==30871== Rerun with --leak-check=full to see details of leaked memory
==30871==
==30871== For counts of detected and suppressed errors, rerun with: -v
==30871== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)
代码如下:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
void fillArray(int* array, int len) {
printf("Filling an array at address %p with %d "
"values\n", array, len);
for (int i = 0; i < len; ++i) {
array[i] = i * 3 + 2;
assert(array[i] == i * 3 + 2);
}
printf("Done!\n");
}
typedef struct {
int a, b, c, d;
} FourInts;
int main(int argc, char* argv[]) {
int array[10];
fillArray(array, 10);
int value;
fillArray(&value, 1);
assert(value == 2);
FourInts four_ints;
four_ints.a = 0;
assert(four_ints.a == 0);
fillArray((int*) &four_ints, 4);
assert(four_ints.a == 2);
assert(four_ints.b == 5);
assert(four_ints.c == 8);
assert(four_ints.d == 11);
int* heap_array = (int*) malloc(sizeof(int) * 5);
fillArray(heap_array, 5);
free(heap_array);
FourInts* heapstruct=(FourInts*)malloc(sizeof(FourInts));
fillArray((int*)&heapstruct,sizeof(FourInts));
free(heapstruct);
return 0;
}
我无法弄清楚内存泄漏是如何发生的。任何有关这方面的帮助将不胜感激!
答案 0 :(得分:2)
heapstruct
已经是一个指针,所以
fillArray((int*)&heapstruct,sizeof(FourInts));
获取指针的地址(产生指向指针的指针)。这会导致你忘记你不应该访问的记忆。
将其更改为
fillArray((int*)heapstruct,sizeof(FourInts));
答案 1 :(得分:1)
除了@ Jefferey的答案之外,你还使用sizeof(FourInts)作为索引内部索引的上限,这会使你超出界限。正确(好吧,不太正确)是sizeof(FourInts)/ sizeof(int)。