-1

I was making a test with pointers in C, and when I tried this code:

int main()
{

    char  * b = "abc";
    char * c = b;

    *c = *(b+1); //problem
    printf("%s",c); 
} 

I got a mistake on the commented line, what I was specting to print was bbc , why that pointer assignment isn't working?

csjr
  • 116
  • 4
  • 12
  • 4
    It is undefined behaviour to modify a string literal. – hmjd Feb 12 '14 at 17:17
  • @BlueMoon the accepted answer to the dup is actually pretty bad, too bad the OP did not accept Keith's answer, which you have to scroll down to find. – Shafik Yaghmour Feb 12 '14 at 17:25
  • @ShafikYaghmour The question *is* dup and there *are* good, accurate answers in that page. That's all I care when I vote to close. What OP accepts is not something I/anyone can influence. – P.P Feb 12 '14 at 17:36
  • @BlueMoon there were perhaps better dups to choose from it seems like few users care about the quality of the dups they choose. Regardless I urged the OP to accept Keith's answer since it is clearly a better answer, so hopefully that will be fixed. – Shafik Yaghmour Feb 12 '14 at 17:40

2 Answers2

4

c is pointing to a string literal, you are not allowed to modify string literals, it is undefined behavior. This is covered in the draft C99 standard section 6.4.5 String literals paragraph 6 which says (emphasis mine):

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

So the behavior of this program is unpredictable.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
0

Variables b and c are both pointing to the same string, which is located in the (read-only) code section of the program.

During run-time, when the CPU executes *c = *(b+1), it performs an illegal memory access.

You should declare this string as a local array in function main, so it will be located in the stack instead:

char b[] = "abc";
barak manos
  • 29,648
  • 10
  • 62
  • 114