top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Pointer in Code segment

+3 votes
517 views

Char *ptr = "Hello"

Here the pointer value will be consider as char constant and stored in Code/Text segment, but why ?
and why not data or stack ?

posted Nov 13, 2013 by sivanraj

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

The value of the pointer means "Hello" becomes the part of text segment.Because we can;t change any value in text segment.

The memory for ptr pointer (4-byte ) allocated at stack(local variable) or at Data Segment (If declared globally ) so we can change the pointer reference of ptr ,
But the value pointing by ptr we can't change till it points to the text segments data.

Take this two example
CODE -1

   char *ptr = "Hello";

    *(ptr + 2) = 'a';

    /* Here it will give segmentation fault 
    Bcoz currently ptr is pointing to data of text segment */

    printf("ptr is %s :\n", ptr);

CODE - 2
But see this snippet When the pointer ptr changed to some other place(stack/Data Segment ) Then You can change the value pointed by this pointer.

     char *ptr = "Hello";

    char str[8] = "World";

     ptr = str;  
    /* Now ptr is not pointing to text segments data */

     *(ptr + 2) = 'a';

    /* Here We can change the value pointer by ptr as
     currently ptr is not pointing to data of text segment 
     rather it is pointing to stack segments data*/

    printf("ptr is %s :\n", ptr);

So conclusion is that text segment data value we should not try to change,so through this the data they are storing permanently.

answer Nov 13, 2013 by Sachidananda Sahu
...