Reputation: 827
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.
Upvotes: 4
Views: 302
Reputation: 19805
p will point to a read-only area of memory which will be allocated on the stack. Moreover the compiler will automatically null-terminate the string adding a '\0' byte at the end.
Not using const is dangerous, in fact the g++ compiler issue an warning for the following code:
#include <stdio.h>
int main(int argc, const char *argv[])
{
char *p = "AString8";
printf("%s\n", p);
printf("Last char: %c hex: %x\n", p[7], p[7]);
printf("Last char + 1: %c hex: %x\n", p[8], p[8]);
return 0;
}
warning: deprecated conversion from string constant to ‘char*’
Program output:
Last char: 8 hex: 38
Last char + 1: hex: 0
Upvotes: 2
Reputation: 182619
That's a string literal. The standard doesn't know about "stack", "heaps" etc - those are implementation details. So there's no "standard" location.
But typically it's not on the stack. It's in a read-only region called text
. And it's not "similar to how static array's are allocated".
Upvotes: 7
Reputation: 11606
The string literal "I didn't malloc..."
is stored in a read-only area of the data segment and p
contains the address of that location.
Upvotes: 2
Reputation: 206508
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...";
Upvotes: 8
Reputation: 96109
The memory is also allocated read-only any attempt to change *p is undefined.
Not generally on the stack though, it would be part of the data segment of the executable
Upvotes: 5