Sunday 2 February 2014

Why do I get a segmentation fault when writing to a string?

The following code receives seg fault on line 2:
  char *str = "string";
str
[0] = 'z';
printf
("%s", str);
While this works perfectly well:
  char str[] = "string";
str
[0] = 'z';
printf
("%s", str);
Tested with MSVC and GCC.

Answers:-

To understand this error or problem you should first know difference b/w the pointer and array so here firstly i have explain you differences b/w them

string array

 char strarray[] = "hello";
In memory array is stored in continuous memory cells, stored as [h][e][l][l][o][\0] =>[] is 1 char byte size memory cell ,and this continuous memory cells can be access by name named strarray here.so here string array strarray itself containing all characters of string initialized to it.in this case here "hello" so we can easily change its memory content by accessing each character by its index value
`strarray[0]='m'` it access character at index 0 which is 'h'in strarray
and its value changed to 'm' so strarray value changed to "mello";
one point to note here that we can change the content of string array by changing character by character but can not initialized other string directly to it like strarray="new string" is invalid

Pointer

As we all know pointer points to memory location in memory , uninitialized pointer points to random memory location so and after initialization points to particular memory location
char *ptr = "hello";
here pointer ptr is initialized to string "hello" which is constant string stored in read only memory (ROM) so "hello" can not be changed as it is stored in ROM
and ptr is stored in stack section and pointing to constant string "hello"
so ptr[0]='m' is invalid since you can not access read only memory
But ptr can be initialised to other string value directly since it is just pointer so it can be point to any memory address of variable of its data type
ptr="new string"; is valid

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More