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);

}
4

2 回答 2

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
于 2013-01-05T17:58:09.887 回答
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.

于 2013-01-05T18:00:09.327 回答