char * ptr = "hello" and char carray[] = "hello"
I was intrigued by this interview question where the reviewer asked if a char * ptr will take more space than a char carray[]. I found the following with gcc 2.96 on ia32:
#include < stdio.h>
static char * ptr = "hello";
int x = 0x41414141;
static char ptr8[] = "hello888";
int y = 0x42424242;
char ptr5[] = "hello";
int z = 0x43434343;
static char ptr8a[8] = "hello888"; // I got confused here between
ptr8 and ptr8a
int u = 0x42424242;
int main(void){
int i;
for(i = 0; i < 9; i ++)
printf("%d %c\n", i, ptr8[i]);
if((unsigned char)ptr8a[8] == 0x42)
printf("not null terminated\n");
if((unsigned char)ptr5[5] != 0x43)
printf("null terminated, aligned on 8 byte boundary\n");
printf("ptr[0] = %c\n", ptr[0]);
}
Executing this (after compiled with gcc 2.96 with -O3)
./ptr_t
0 h
1 e
2 l
3 l
4 o
5 8
6 8
7 8
8
not null terminated
null terminated, aligned on 8 byte boundary
ptr[0] = h
Now I did a binary dump of the ELF binary file, here is the
interesting sections:
Contents of section .rodata:
80485e0 03000000 01000200 00000000 00000000 ................
80485f0 00000000 00000000 00000000 00000000 ................
8048600 68656c6c 6f002564 2025630a 006e6f74 hello.%d %c..not
8048610 206e756c 6c207465 726d696e 61746564 null terminated
8048620 0a000000 00000000 00000000 00000000 ................
8048630 00000000 00000000 00000000 00000000 ................
8048640 6e756c6c 20746572 6d696e61 7465642c null terminated,
8048650 20616c69 676e6564 206f6e20 38206279 aligned on 8 by
8048660 74652062 6f756e64 6172790a 00707472 te boundary..ptr
8048670 5b305d20 3d202563 0a00 [0] = %c..
Contents of section .data:
804967c 00000000 00000000 cc960408 00000000 ................
804968c 00860408 41414141 68656c6c 6f383838 ....AAAAhello888
804969c 00000000 42424242 68656c6c 6f000000 ....BBBBhello...
80496ac 43434343 68656c6c 6f383838 42424242 CCCChello888BBBB
RVA 804968c -> 00860408 (08048600) ->"hello"
<< Home