Hi. Below are two pieces of code. This first one works fine:

char str[] = "Hello World";
    char *b;
    b = &(str[3]);
    *b = '3';
    printf("%s\n", str);

However this second one results in a segmentation fault.

char *str = "Hello World";
    char *b;
    b = &(str[3]);
    *b = '3';
    printf("%s\n", str);

The difference is in the definition of the variable str. Why does one method work fine and the other result in a segmentation fault? When is it best to use a str[] definition and the *str definition?

Recommended Answers

All 2 Replies

The first is local data you can edit (since the array is local data).

The second is a local pointer to global, static (constant) data. You are not allowed to modify constant data.

If you have GNU C, you can compile with -fwritable-strings to keep the global string from being made constant, but this is not recommended.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.