0

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
Why do I get a segmentation fault when I try to modify a string constant?

I was trying to run the following two codes and I am getting a segmentation fault with file2.c but with file1.c I am not getting any fault. Can somebody explain what is the difference between the following codes :

file1.c

#include <stdio.h>

int main()
{
    int i;
    char  string[11] = {"HelloThere"};
    string[10] = '\0';
    for(i =0;i<5;i++)
    {
        string[i] = 'a';
    }
    printf("%s\n",string);
}

and :

file2.c

#include <stdio.h>

int main()
{
    int i;
    char * string;
    string = "HelloThere";

    for(i =0;i<5;i++)
    {
        string[i] = 'a';    
    }
    printf("%s",string);

}
Community
  • 1
  • 1
Deepankar Bajpeyi
  • 5,661
  • 11
  • 44
  • 64
  • 2
    This question is a duplicate hundreds of times over. – Carl Norum Jan 05 '13 at 17:58
  • 2
    @Oli - I think this one is better: [Why do I get a segmentation fault when writing to a string?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string) Perhaps the best question is "Why didn't the OP even bother to search first?" – Carl Norum Jan 05 '13 at 17:58

2 Answers2

3

This is because the assignment

char  string[11] = {"HelloThere"};

copies the string constant into a writable memory, while

char * string = "HelloThere";

leaves it in the read-only memory. While it is absolutely OK to write to the writable memory (duh!) writing to read-only memory is undefined behavior, and may trigger a crash.

Note that you do not need to specify the size of your string explicitly, unless you want to allocate more memory than is required for your string literal:

char  string[] = {"HelloThere"}; // <<== The size is empty
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1
string = "HelloThere";

then

string[i] = 'a';

is wrong - you're trying to modify a string literal, which you can't. This results in undefined behavior, so anything can happen, including crashes.

However,

char sring[11] = "HelloThere";

creates an auto array (copying the contents of the string in it beforehands) and that's writable, it's allowed to modify their elements.