Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this line of code work?

So I was recently looking at someone's code and I saw that the compiler didn't complain nor were there any run time errors with the following:

const char *p = "I didn't malloc...";

The code above works but I was wondering how. Here is what I think is happening. Can anyone confirm this please?

So "I didn't malloc..." gets allocated statically on the stack at compile time and the address to that is passed to the pointer p. Similar to how static array's are allocated. I am 90% sure of this, but some confirmation would help.

Thanks.

like image 439
Edwin Avatar asked Nov 29 '22 09:11

Edwin


1 Answers

You have an string literal "I didn't malloc..." located somewhere in the read only memory(exactly where is Implementation defined) which is pointed to by the pointer p.

Important thing to note is any attempt to change this string literal will result in Undefined Behavior.

In fact in C++ it is deprecated to declare a string literal like you did.
So in C++ You should a const qualifier in place like:

const char *p = "I didn't malloc...";
like image 68
Alok Save Avatar answered Dec 13 '22 11:12

Alok Save