1

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
What is the difference between char a[] = “string”; and char *p = “string”;

Can anyone point out the problem in following program:

#include <stdio.h>

int main()
{
    char *c = "Hello World!! !!";
    char c2 = 'X';
    while(c)
    {
        if(*c == ' ')
        {
            printf("%s",c);
            *c = c2;
        }
        c++;
    }
    return 0;
}

It crashes at *c = c2; with following error :

Thread [1] (Suspended : Signal : EXC_BAD_ACCESS:Could not access memory)    
    main() at mainclass.cpp:64 0x100000d74  

I used GCC as compiler on MAC OSX and Eclipse as IDE.

Community
  • 1
  • 1
Mohammad
  • 1,636
  • 1
  • 13
  • 17

2 Answers2

3

In your code, c points to a string literal. The line *c = c2 tries to modify the string literal, which is undefined behaviour. One possible manifestation of the undefined behaviour is that string literals are put into read-only memory and you get a SIGSEGV or similar.

If you change the code as follows, it should work:

char arr[] = "Hello World!! !!";
char* c = arr;

Now c points into an array. Unlike string literals, it is permissible to modify the contents of an array.

Lastly, your while-loop is incorrectly conditioned on the value a pointer, not the value it points to. You're looking for a null-terminator ('\0'). It should look like this:

while (*c)
{
    ...
    c++;
}
WhozCraig
  • 65,258
  • 11
  • 75
  • 141
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

When you do: char *c = "Hello World!! !!"; then c is a pointer that points to a memory that is in the code part, so you can't change it.

But if you have char c[] = "Hello World!! !!"; then c is an array of chars that are on the stack, so you can change it.

In this case, it is better to do: char const *c = "Hello World!! !!"; because then, if you try to change the string as you are doing, your program won't crash, it will arise a compiler error and won't run the program, which is much better.

Maroun
  • 94,125
  • 30
  • 188
  • 241