Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

unix

libc

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?

like image 909
theprole Avatar asked Nov 08 '10 23:11

theprole


1 Answers

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.

like image 173
Ed S. Avatar answered Sep 21 '22 02:09

Ed S.