Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I edit a char in a char*?

Tags:

c

gcc

c-strings

Below is an exceedingly simple example. It compiles fine using gcc on Mac OS X (Snow Leopard). At runtime it outputs Bus error: 10. What's happening here?

char* a = "abc";
a[0] = 'c';
like image 836
Nate Avatar asked Sep 20 '11 05:09

Nate


5 Answers

Your code sets a to a pointer to "abc", which is literal data that can't be modified. The Bus error occurs when your code violates this restriction, and tries to modify the value.

try this instead:

char a[] = "abc";
a[0] = 'c';

That creates a char array (in your program's normal data space), and copies the contents of the string literal into your array. Now you should have no trouble making changes to it.

like image 179
Lee Avatar answered Sep 25 '22 10:09

Lee


You are trying to modify a string constant. Use this instead:

char a[] = "abc";
a[0] = 'c';
like image 24
Vaughn Cato Avatar answered Sep 24 '22 10:09

Vaughn Cato


This

char* a = "abc";

relies on a dangerous implicit conversion from const char[] (the type of a string literal) to char*. (In C++ this conversion has been deprecated for more than a decade. I don't know about C, though.)

A string literal must not be altered.

like image 20
sbi Avatar answered Sep 23 '22 10:09

sbi


char *str = "string"; In such a case it is treated as a read only literal. It is similar to writing const char *str = "string". Which is to say that the value pointed to by the pointer str is a constant. Trying to edit will result in BUS ERROR.

like image 22
Anoop Menon Avatar answered Sep 25 '22 10:09

Anoop Menon


char *a = "abc" is a constant string stored in the .data section of an ELF binary. You are not allowed to modify this memory and if you do you incur undefined behavior in some cases it will give no error but not modify the memory in your case you get a bus error because you are attempting to access memory that you normally cannot (for writing purposes).

like image 42
Jesus Ramos Avatar answered Sep 25 '22 10:09

Jesus Ramos