C ++程序什么都不做,但是Valgrind显示内存分配

问题描述 投票:1回答:1

[当我发现奇怪的事情时,我正在与Valgrind嬉戏:我的C ++程序什么也不做,但是有1个内存分配和1个空闲空间。

我的简单程序:

int main() {
  return 0;
}

使用g ++编译并使用Valgrind检查时

> g++ main.cpp
> valgrind --leak-check=full --track-origins=yes ./a.out

==40790== Memcheck, a memory error detector
==40790== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==40790== Using Valgrind-3.16.0.GIT and LibVEX; rerun with -h for copyright info
==40790== Command: ./a.out
==40790== 
==40790== 
==40790== HEAP SUMMARY:
==40790==     in use at exit: 0 bytes in 0 blocks
==40790==   total heap usage: 1 allocs, 1 frees, 72,704 bytes allocated
==40790== 
==40790== All heap blocks were freed -- no leaks are possible
==40790== 
==40790== For lists of detected and suppressed errors, rerun with: -s
==40790== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

我的问题:我的程序什么都不做。 alloc和free来自何处?

有趣的是,用gcc编译的同一程序显示了零分配和释放:

> gcc main.c
> valgrind --leak-check=full --track-origins=yes ./a.out
==40740== Memcheck, a memory error detector
==40740== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==40740== Using Valgrind-3.16.0.GIT and LibVEX; rerun with -h for copyright info
==40740== Command: ./a.out
==40740== 
==40740== 
==40740== HEAP SUMMARY:
==40740==     in use at exit: 0 bytes in 0 blocks
==40740==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==40740== 
==40740== All heap blocks were freed -- no leaks are possible
==40740== 
==40740== For lists of detected and suppressed errors, rerun with: -s
==40740== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

后续问题:为什么对于同一段代码,两个内存分配不同?

编译器:gcc(GCC)10.1.0valgrind:valgrind-3.16.0.GIT

c++ gcc memory-leaks valgrind
1个回答
1
投票

The main function是代码的入口点。它不一定是(很少是)正在加载程序的操作系统进程的切入点。

在调用主函数之前,通常会先运行大量代码来设置标准库所需的内容(例如,设置标准I / O流,并从操作系统中获取实际参数)。

并且必须注意,main函数的调用与其他任何函数一样。一旦返回,它将返回到初始化代码,该初始化代码现在将在自身之后进行清理(例如释放可能已分配的内存,并关闭流等)。

© www.soinside.com 2019 - 2024. All rights reserved.