Question

I have used this line of code many times (update: when string was a parameter to the function!), however when I try to do it now I get a bus error (both with gcc and clang). I am reproducing the simplest possible code;

char *string = "this is a string";
char *p = string;
p++;
*p='x'; //this line will cause the Bus error
printf("string is %s\n",string);

Why am I unable to change the second character of the string using the p pointer?

Was it helpful?

Solution

You are trying to modify read only memory (where that string literal is stored). You can use a char array instead if you need to modify that memory.

char str[] = "This is a string";
str[0] = 'S'; /* works */

I have used this line of code many times..

I sure hope not. At best you would get a segfault (I say "at best" because attempting to modify readonly memory is unspecified behavior, in which case anything can happen, and a crash is the best thing that can happen).

When you declare a pointer to a string literal it points to read only memory in the data segment (look at the assembly output if you like). Declaring your type as a char[] will copy that literal onto the function's stack, which will in turn allow it to be modified if needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top