C Array/String Initialization

A question came up in lab today about what happens with the following C line at compilation and at run time:

char str[80] = "hello";

People doubted that the effect of this line would be to reserve space in memory for 80 char and initialize the first six of them with:

{'h', 'e', 'l', 'l', 'o', '\0'}

So, in order to settle this dispute, I wrote this short C program:

#include 
char str[80] = "hello";
char *other = "thisone";
int i;
 
int main(int argc, char *argv[]) {
  printf("str contains = %s\n", str);
  printf("str points to = %p\n", str); 
 
  for (i=0; i < 80; i++)
    printf("%p <- str[%d] = %c (%d)\n", &str[i], i, str[i], str[i]);

  printf("other contains = %s\n", other);
  printf("other points to = %p\n", other);
  printf("i contains = %d\n", i);
  printf("i resides at = %p\n", &i);

  return 0;
}

 

This little, seemingly silly program was enough to test some assumptions. The output it produced was:

~/Code/test > ./memory
str contains = hello
str points to = 0x100001068
0x100001068 < - str[0] = h (104)
0x100001069

I also took a peek at the symbol table in this program with nm:

~/Code/test > nm memory
0000000100000f39 s  stub helpers
0000000100001048 D _NXArgc
0000000100001050 D _NXArgv
0000000100001060 D ___progname
0000000100000000 A __mh_execute_header
0000000100001058 D _environ
                 U _exit
00000001000010c0 S _i
0000000100000d44 T _main
00000001000010b8 D _other
                 U _printf
0000000100001000 s _pvars
0000000100001068 D _str
                 U dyld_stub_binder
0000000100000d08 T start

My interpretation from these results is that the line

char str[80] = "hello";

does indeed allocate (in the data segment) space for 80 char and initializes the first six to:

{'h', 'e', 'l', 'l', 'o', 0}

In fact, what it does is to initialize the first 5 positions with 'h', 'e', 'l', 'l', 'o' and all the remaining 75 elements of the array with byte value 0. This observation is consistent with what I found at:

http://stackoverflow.com/questions/201101/how-to-initialize-an-array-in-c

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.