Possible Duplicate:
C Program String Literals
Bus error: 10 error
Using Xcode 4.5.2 for C, I thought
char * string = "abc";
string[0] = 'f';
and
char string[4] = "abc";
string[0] = 'f';
were equivalent. But the first line gives me an error:
EXC_BAD_ACCESS (code = 2, address = 0x100 ...)
And the second line gives me NO error. I thought these were equivalent in straight C. What's going on?
int main (void) {
char * string = "abc";
string[0] = 'f';
} // main
They are not the same.
char* s = "bla"
The above has s point to the memory location where the string literal is stored. Since this is a read-only memory (the literal is constant) the write to it fails.
char s[4] = "bla";
This fills the buffer s
(which was allocated on the stack) with the contents of the literal. You can write to this buffer since it isn't const memory.
The reason why the first syntax is considered legal and doesn't raise an error related to const correctness, has to do with maintaining backwards compatibility with older versions of c.
These are not equivalent as you've discovered. The first is undefined behavior, as string constants are constant (that is const char * const
). They may be in read-only memory (bad access, address 0x100 is a nice clue), which you are trying to modify through the first string
(which is a char *
). The second string
is actually an array of char
which has storage (in this case on the stack) which may be modified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With