Bus error when trying to access a character in a string in C

I have used this line of code many times (update: when the line was a parameter for the function!), However, when I try to do this, I get a bus error (with both 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 can't I change the second character of a string with a p-pointer?

+4
source share
1 answer

You are trying to change read-only memory (where this string literal is stored). Instead, you can use a char array if you need to change this memory.

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

I have used this line of code many times.

I hope not. At best, you get segfault (I say โ€œat bestโ€ because trying to change readonly memory is unspecified behavior, in which case something can happen, and an accident is the best thing that can happen).

When you declare a pointer to a string literal, it indicates that only memory is read in the data segment (look at the assembly if you want). Declaring your type as char [] will copy this literal in the function stack, which in turn will allow it to be changed if necessary.

+9
source

All Articles