Variable initialization in C

I’m feel that I am starting to get the hold of C programming. But every now and then, I get these “ahaaa” moments, that I am a bit embarrassed about. One of these “aha”‘s I experienced today is how/when C handles initialization of variables where you don’t explicitly initialize them yourself.

Consider this code:

int var1;
int main(char **argv, int argc) {
  static int var2;
  int var3;
  return 0;

Here i deliberately did not initialize any of the variables to make an example. The first two variables will automatically be initialized with 0 before your main() function is executed. The last variable lives in the stack and will not be initialized unless you explicitly do it yourself. So it will probably have a ‘random’ value. Thats kind of handy to know about ;) I feel like this probably is one of the first things you usually learn about C, but I had totally missed this. Nice to know. Also if you use Valgrind to check your code, it can be very good at following uninitialized stack variables. It will actually follow uninitialized memory bit-wise.

First I thought the memory was initialized to 0 at compile-time, but after some reading, I learnt that the compiler records the amount of uninitialized memory for global and static variables, and stores the amount of data required in the BSS segment of the program. This way the executable will not grow in size in line with the amount of uninitialized data. For this reason some people call the BSS segment for the “Better Save Space” segment.

Posted November 13th, 2011 in C, Tips & tricks.

Leave a response: