Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char * vs char[] [duplicate]

Tags:

c

char

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
like image 221
Cary Rader Avatar asked Dec 27 '22 10:12

Cary Rader


2 Answers

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.

like image 189
StoryTeller - Unslander Monica Avatar answered Dec 28 '22 22:12

StoryTeller - Unslander Monica


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.

like image 43
ldav1s Avatar answered Dec 28 '22 23:12

ldav1s