我正在阅读“学习艰难的道路”第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
在本书和其他人的代码中,它显示了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;
}
我不明白为什么需要为这件事分配1kb的空间。
这让我烦恼,我想知道发生了什么。
感谢任何帮助。谢谢你的时间!
编辑:1KB,而不是1MB
答案 0 :(得分:6)
这是1KB,而不是1MB ..这些天的记忆不多(35年前,它已经很多了)。
至于为什么它使用那么多:write
使用缓冲的I / O,它分配缓冲区。确切的答案实际上取决于平台,因为c库和操作系统会有所不同。但是,如果你只使用系统调用编写相同的程序,例如。 printf
代替Scenario: given I have added the following asset
Given I have added the following asset
"""
{"$class":"org.acme.sample.SampleAsset", "assetId":"1", "owner":"alice@email.com", "value":"10"}
"""
Then I should have the following asset
"""
{"$class":"org.acme.sample.SampleAsset", "assetId":"1", "owner":"alice@email.com", "value":"10"}
"""
,您可能会看到内存使用量下降。
答案 1 :(得分:2)
printf
在实际将数据写入标准输出之前缓冲I / O(如提到的@little_birdie)。缓冲I / O是指在将应用程序(用户空间)传输到内核之前临时存储I / O操作的做法,这可能很慢。为了最大限度地减少这些所谓的系统调用,您的应用程序将提前询问此类内存。
系统的某些功能完全禁用此功能,甚至可能是历史系统根本没有缓冲I / O(尽管我不熟悉任何功能),这种情况并不少见。
如果你想在你的stdout
上禁用缓冲(以及因此分配“0”字节的堆内存),你可以像setbuf
那样请求它:
#include <stdio.h>
int main()
{
int distance = 100;
setbuf(stdout, NULL);
printf("You are %d miles away.\n", distance);
return 0;
}
如果您想了解更多相关信息,请查看优秀的Linux Programming Interface