How does this line of code work?

So, I recently looked at someone's code, and I saw that the compiler did not complain and there were no runtime errors with the following:

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

The code above works, but I was wondering how to do this. Here is what I think is going on. Can someone please confirm this?

So, "I was not malloc ..." is statically pushed onto the stack at compile time, and the address to which is passed to the p pointer. Similar to how a static array is allocated. I am 90% sure of this, but some confirmation will help.

Thanks.

+4
source share
5 answers

This is a string literal. The standard does not know about "stack", "heap", etc. These are implementation details. Therefore, there is no "standard" location.

But usually this is not on the stack . It is located in a read-only area called text . And this is not "similar to how a static array is allocated."

+7
source

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

It is important to note that any attempt to modify this string literal will result in Undefined Behavior .

Actually in C ++, it is deprecated to declare a string literal, as you did.
So in C ++ you have to choose a const qualifier, for example:

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

Memory is also read-only. Any attempt to change * p is undefined.
However, typically, on the stack, it would be part of the data segment of the executable

+5
source

The string literal "I didn't malloc..." is stored in the read-only area of ​​the data segment, and p contains the address of this location.

+2
source

p will point to a read-only memory area that will be allocated on the stack. In addition, the compiler will automatically terminate the zero of the line, adding the byte '\ 0' at the end.

Not using const is dangerous, in fact the g ++ compiler generates a 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 
+2
source

Source: https://habr.com/ru/post/1385668/


All Articles