Valgrind: Why does my tiny programming take up so much space?

I read chapter 4 of โ€œLearn C the Hard Way,โ€ where we get started with valgrind.

One thing I noticed is that my very small programs allocate 1024 bytes:

==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 

In the book and in the code of other people, 0 allocated bytes are displayed.

Here is the code:

 #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; } 

I do not understand why this thing requires 1 kilobyte of space.

This bothers me, and I would like to know what is going on.

Any help is appreciated. Thank you for your time!

Edit: 1 KB, not 1 MB

+5
source share
2 answers

This 1KB, not 1MB .. which is not much memory these days (35 years ago there were a lot).

What is the reason for this: printf uses buffered I / O that allocates buffers. The exact answer really depends on the platform, as c libraries and operating systems will be different. But if you were to write the same program using only system calls, for example. write instead of printf , you will probably see that memory usage is declining.

+6
source

printf buffers I / O before it actually writes data to standard (as @little_birdie mentioned). Buffered I / O refers to the practice of temporarily storing I / O operations in your application (user space) until it is transferred to the kernel, which can be slow. To minimize these so-called system calls, your application will request such memory ahead of time.

Often, some system functions may completely disable this function, or even, perhaps, for a historical system, do not have buffered I / O at all (although I am not familiar with any).

If you want to disable buffering on stdout here (and thus allocate "0" bytes of heap memory), you can request it with setbuf as follows:

 #include <stdio.h> int main() { int distance = 100; setbuf(stdout, NULL); printf("You are %d miles away.\n", distance); return 0; } 

If you want to know more about this, check out the great Linux Programming Interface.

+2
source

Source: https://habr.com/ru/post/1269843/


All Articles