为什么valgrind将64位程序中指针的大小报告为4个字节

时间:2012-10-21 14:33:38

标签: c++ valgrind

我编写了一个测试C ++程序来检查valgrind的输出。代码是

#include <iostream>

void f() {
    int *pp = new int(1);
    std::cout << "pp is " << *pp << "\n";
}

int main() {
    f();
    return 0;
}

我使用的valgrind命令是

valgrind --leak-check=yes ./a.out

Valgrind的输出

==2255== HEAP SUMMARY:
==2255==     in use at exit: 4 bytes in 1 blocks
==2255==   total heap usage: 1 allocs, 0 frees, 4 bytes allocated
==2255== 
==2255== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2255==    at 0x4C2B1C7: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2255==    by 0x400786: f() (in /run/shm/a.out)
==2255==    by 0x4007CC: main (in /run/shm/a.out)
==2255== 
==2255== LEAK SUMMARY:
==2255==    definitely lost: 4 bytes in 1 blocks
==2255==    indirectly lost: 0 bytes in 0 blocks
==2255==      possibly lost: 0 bytes in 0 blocks
==2255==    still reachable: 0 bytes in 0 blocks
==2255==         suppressed: 0 bytes in 0 blocks

我使用的是Ubuntu机器:     Linux Sun 3.2.0-27-generic#43-Ubuntu SMP Fri 7月6日14:25:57 UTC 2012 x86_64 x86_64 x86_64 GNU / Linux

gcc版本“4.6.3”

gcc参数我使用了“-g -m64”

我认为它应该是8个字节,对吗?

2 个答案:

答案 0 :(得分:2)

不,除非你的平台上有sizeof(int)==8,否则它不应该是八个字节。

您正在分配和泄漏单个int,而不是指针。

答案 1 :(得分:0)

您不分配指针数组,而是分配大小为1的整数数组。所以你只在内存中分配一个整数的大小。唯一的指针是存储新分配数组的地址的局部变量。

如果要分配指针,请执行void **arr = new void*[1];