【发布时间】:2017-10-31 12:04:00
【问题描述】:
我正在用 C 编写一些简单的代码来测试一些内存分配和指针:
#include <stdlib.h>
#include <stdio.h>
int *randomAlloc(int n) {
int *address = NULL, i = 0;
address = malloc (n * sizeof(int));
for (i = 0; i < n ; i++){
*(address + i) = i ;
}
return address;
}
int main(int argc, char* argv[] ) {
int *address;
int n;
printf("Type vector size: ");
scanf("%d", &n);
address = randomAlloc(n);
free(address);
}
但由于某种原因,当我输入 4 作为输入 valgrind 输出时:
==2375== Memcheck, a memory error detector
==2375== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==2375== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==2375== Command: ./a.out
==2375==
Type vector size: 4
==2375==
==2375== HEAP SUMMARY:
==2375== in use at exit: 0 bytes in 0 blocks
==2375== total heap usage: 3 allocs, 3 frees, 2,064 bytes allocated
==2375==
==2375== All heap blocks were freed -- no leaks are possible
==2375==
==2375== For counts of detected and suppressed errors, rerun with: -v
==2375== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
代码中只有一个 alloc 和一个 free。由于 n = 4,我希望它分配 4*4(sizeof(int))=16 字节。这是哪里来的?
【问题讨论】:
-
输入
1或2...它仍然是一样的。唯一会改变的是2,064 bytes allocated。现在看看并想一想,为什么。 -
我无法重现您描述的行为。当我构建你的代码并在 Valgrind 下运行它时,它会报告一个分配和一个空闲,正如你所期望的那样。
-
@JohnBollinger 不在我的系统上(linux mint)。如果我输入
2我有:total heap usage: 3 allocs, 3 frees, 2,056 bytes allocated如果我输入3我有:total heap usage: 3 allocs, 3 frees, 2,060 bytes allocated..... 等等。2,056=>2,060=> `2064`
标签: c malloc valgrind free dynamic-allocation