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

标签 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 ;
    }
    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)

代码中只有一项分配和一项释放。当 n = 4 时,我希望它分配 4*4(sizeof(int))=16 字节。这是从哪里来的?

最佳答案

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

许多标准 I/O 实现都会分配缓冲区供 printf() 和/或 scanf() 使用,这可能就是您要计算的数字的原因看见了。

关于c - Valgrind 显示分配的内存比实际分配的内存多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44271967/

相关文章:

c - malloc(0) 真的有效吗?

linux - 在linux中,malloc给你谁的数据?

c - fork after malloc in parent...子进程需要释放它吗?

c++ - libGL 堆使用

c++ - 正确锁定从多个线程调用其自己的成员函数的类。 (我需要锁定访问 "this"指针吗?)

c - 什么是实现简单的基于 clone() 的多线程库的好方法?

c - 为什么我的代码无法通过我的函数访问矩阵的元素?

c++ - 为什么我们不能在 C 或 C++ 代码中使用直接寻址?

c++ - 使用 c 更新文件

c++ - initializer_list 中的未初始化值(编译器错误?)