bus error when trying to access character on a string in C bus error when trying to access character on a string in C unix unix

bus error when trying to access character on a string in C


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.