我正在阅读"学习艰难的道路"第4章,我们开始与valgrind合作.
我注意到的一件事是我的小程序正在分配1,024个字节:
==19896== HEAP SUMMARY:
==19896== in use at exit: 0 bytes in 0 blocks
==19896== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
Run Code Online (Sandbox Code Playgroud)
在本书和其他人的代码中,它显示了0个字节的分配.
这是代码:
#include <stdio.h>
int main(int argc, char *argv[])
{
int distance = 100;
// this is also a comment
printf("You are %d miles away.\n", distance);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么需要为这件事分配1kb的空间.
这困扰我,我想知道发生了什么.
任何帮助表示赞赏.谢谢你的时间!
编辑:1KB,而不是1MB
这是1KB,而不是1MB ..这些天没有太多记忆(35年前,它是很多).
至于为什么它使用那么多:printf使用缓冲的I/O,它分配缓冲区.确切的答案实际上取决于平台,因为c库和操作系统会有所不同.但是,如果你只使用系统调用编写相同的程序,例如.write而不是printf,你可能会看到内存使用率下降.