Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

valgrind: Why is my tiny programming allocating so much space?

Tags:

c

I'm reading through chapter 4 of "Learn C the Hard Way", where we start to work with valgrind.

One thing I noticed is that my very small programs are allocating 1,024 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 other people's code it shows 0 bytes allocated.

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 don't understand why there needs to be 1kb of space allocated for this thing.

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

Any help is appreciated. Thanks for your time!

Edit: 1KB, not 1MB

like image 840
Lee Gaines Avatar asked Jul 14 '17 18:07

Lee Gaines


1 Answers

That's 1KB, not 1MB.. which isn't much memory these days (35 years ago, it was a lot).

As to why it's using that much: printf uses buffered I/O, which allocates buffers. The exact answer really depends upon the platform since c libraries and operating systems will vary. But if you were to write the same program using just system calls eg. write instead of printf, you'd probably see the memory usage go down.

like image 174
little_birdie Avatar answered Nov 05 '22 19:11

little_birdie