Tuesday, September 28, 2010

char*ptr Vs char ptr[]

Why as follows program works in Sunstudio C compiler but segmentation faults in gcc:

int
main()
{
char *ptr = "hello";
ptr[2] = 'v';
printf("ptr = %s\n", ptr);
return 0;
}

# gcc charPtr.c
# ./a.out
Segmentation Fault (core dumped)
# cc charPtr.c
# ./a.out
ptr = hevlo

You can get a segmentation fault with Sun Studio as well if you use
-xstrconst. This option makes the string nonwritable.

You can't write into string constants as per the ANSI C standard, but the
Sun compiler will let you do it unless you specify -xstrconst.

ptr' itself is allocated in the stack. However, the literal
string "bhushan" is stored in .rodata (static memory area).

You actually have two objects there -- a pointer, which is itself mutable, and a constant string, which might or might not be, depending on compiler option.

Here pointer ptr is pointing to the "bhushan" that is stored in read only memory therefore you are trying to change the read only memory conents. This will obviously gives you Core dump.

To work this do as follows:
1. Change your declaration as follows:
char * ptr= "bhushan" to char ptr[]= "bhushan"
OR
2. Allocate the memory for the ptr first using malloc.

In the above two points this will works using both cc and gcc compiler. In these cases "bhushan" will stored in Readonly memory and and "bhushan" will copied to the stack memory allocated for ptr when main is called.
Therfor you can changes this string using ptr on stack.

No comments: