Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding C-strings & string literals in C++

I have a few questions I would like to ask about string literals and C-strings.

So if I have something like this:

char cstr[] = "c-string";

As I understand it, the string literal is created in memory with a terminating null byte, say for example starting at address 0xA0 and ending at 0xA9, and from there the address is returned and/or casted to type char [ ] which then points to the address.

It is then legal to perform this:

for (int i = 0; i < (sizeof(array)/sizeof(char)); ++i)
    cstr[i] = 97+i;

So in this sense, are string literals able to be modified as long as they are casted to the type char [ ] ?

But with regular pointers, I've come to understand that when they are pointed to a string literal in memory, they cannot modify the contents because most compilers mark that allocated memory as "Read-Only" in some lower bound address space for constants.

char * p = "const cstring";
*p = 'A'; // illegal memory write

I guess what I'm trying to understand is why aren't char * types allowed to point to string literals like arrays do and modify their constants? Why do the string literals not get casted into char *'s like they do to char [ ]'s? If I have the wrong idea here or am completely off, feel free to correct me.

like image 212
Bobby Barjasteh Avatar asked May 19 '26 22:05

Bobby Barjasteh


1 Answers

The bit that you're missing is a little compiler magic where this:

char cstr[] = "c-string"; 

Actually executes like this:

char *cstr = alloca(strlen("c-string")+1);
memcpy(cstr,"c-string",strlen("c-string")+1);

You don't see that bit, but it's more or less what the code compiles to.

like image 69
tylerl Avatar answered May 22 '26 11:05

tylerl