I think one of the most common things to do in C is to perform static memory allocation, even if one is not aware of it. C does some cool stuff with static memory allocation and understanding what happens behind the scenes definitely helps reduce bugs.

Below I have provided some example code that I compiled with GCC 3.4.6. The point of this program is to show how static memory allocation works. Try to execute the code in your head before compiling it and running it.

#include <stdio.h>
#include <string.h>
 
int main (int argc, char * argv[])
{
  char * numbers = "1234567890";
  char * letters = "abcdefghij";
  char * a;
  char * b;
  char * c;
  char tmp;
 
  if (strcmp(letters, "abcd") == 0)
    {
      printf("This should not print although we will use it later!\n");
    }
 
  /* 
     TEST 1:
 
     Print address of numbers and letters the addresses
     should be 11 bytes apart.
  */
  printf("numbers: %p\n", numbers);
  printf("letters: %p\n", letters);
  printf("diff:    %d bytes\n", (letters - numbers));
 
  /* 
     TEST 2:
 
     A and B should be the same address because they
     reference the same static value 
  */
 
  a = "1234567890";
  b = numbers;
 
  printf("a:       %p\n", a);
  printf("b:       %p\n", a);
 
 
  /* 
     EXERCISE 1:
 
     Take a moment to look at the following code
     and figure out what will be printed to the
     screen
  */
 
  c = "abcd";
 
  for(a = numbers; a < c + 5; a++)
    {
      /* get the character that 'a' points to */
      tmp = a[0];
 
      switch (tmp)
        {
        case '\0':
          printf("\\0");
          break;
        case '\n':
          printf("\\n");
          break;
        case '\r':
          printf("\\r");
          break;
        default:
          printf("%c", tmp);
          break;
        }
    }
 
  printf("\n");
 
  return 0;
}

The key to understanding this is that each variable in double quotes is put into a ’static’ section of the compiled binary in the order which they were declared. The loop that I write iterates over the first three static variables and prints them out highlighting the null terminating character \0. It’s important to note that the compiler tightly packs each static value separating each string only by a null terminating \0 character. The point of this static data section is that it will be immutable.

As an exercise, Try changing the c + 5 in the for loop to c + 10 and guess what the next 4 characters will be.

On unix-like systems, attempting to write to this static section will result in segmentation faults. For example, if I try to do numbers[0] = ‘@’, I should get a segmentation fault. However, one could copy ‘numbers’ into a variable pointing to the heap or stack and perform this operation just fine.