Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C Valgrind显示分配的内存比实际分配的内存多_C_Malloc_Valgrind_Free_Dynamic Allocation - Fatal编程技术网

C Valgrind显示分配的内存比实际分配的内存多

C Valgrind显示分配的内存比实际分配的内存多,c,malloc,valgrind,free,dynamic-allocation,C,Malloc,Valgrind,Free,Dynamic Allocation,我正在用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 ; }

我正在用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);
}
代码中只有一个alloc和一个free。当n=4时,我希望它分配4*4(sizeof(int))=16字节。这是从哪里来的?

Valgrind跟踪应用程序中发生的所有内存分配,包括C库内部进行的内存分配。它不(也不能)局限于您显式地进行的分配,因为C库可以返回指向其内部分配的内存的指针


许多标准I/O实现将分配缓冲区供
printf()
和/或
scanf()
使用,这可能是您看到的数字的原因。

键入
1
2
…它仍然是一样的。它唯一会改变的是分配的2064字节。现在看一看,想一想,为什么。我无法重现你描述的行为。当我构建您的代码并在Valgrind下运行时,它会报告一个分配和一个空闲,正如您所期望的那样。@JohnBollinger不在我的系统(LinuxMint)上。如果我键入
2
我有:
总堆使用率:3个allocs,3个frees,分配了2056字节
如果我键入
3
我有:
总堆使用率:3个allocs,3个frees,分配了2060字节
。。。。。等等
2056
=>
2060
=>`2064`@Dashwuff解释的是,如果删除
scanf()
部分,您将只有两个alloc,而不是三个。或者最好也删除
printf()
。尝试下面的方法,您将看到以下区别
==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)