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:

C

1

charstr[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:

C

1

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

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

C

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#include <stdio .h>

charstr[80]="hello";

char*other="thisone";

inti;

intmain(intargc,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);

return0;

}

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

1

2

3

4

5

~/Code/test&gt;./memory

str contains=hello

str points to=0x100001068

0x100001068&lt;-str[0]=h(104)

0x100001069

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

~/Code/test&gt;nm memory

0000000100000f39sstub helpers

0000000100001048D_NXArgc

0000000100001050D_NXArgv

0000000100001060D___progname

0000000100000000A__mh_execute_header

0000000100001058D_environ

U_exit

00000001000010c0S_i

0000000100000d44T_main

00000001000010b8D_other

U_printf

0000000100001000s_pvars

0000000100001068D_str

Udyld_stub_binder

0000000100000d08Tstart

My interpretation from these results is that the line

C

1

charstr[80]="hello";

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

C

1

{'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: