Char Array VS Char *

This is a question based on answers to a question:

const char myVar * vs. const char myVar []

const char* x = "Hello World!"; const char x[] = "Hello World!"; 

Now I understand the difference, but my new questions are:

(1) What happens to the β€œHello World” line in the first line if I reassign x? Nothing will indicate this on this issue - will it be destroyed when the region is completed?

(2) Besides the constant, how are the values ​​in the two examples stored differently in memory by the compiler?

+6
source share
3 answers

Accommodation "Hello World!" in your code causes the compiler to include this line in the compiled executable. When the program is executed, this line is created in memory before the main call and, I believe, even before the assembly is called on __start (which starts with the start of the static initializers). The contents of char * x not allocated using new or malloc , or in the frame of the main stack, and therefore cannot be unallocated.

However, a char x[20] = "Hello World" declared inside a function or method is allocated on the stack, and while in scope there will actually be two copies of this "Hello World" in memory - one previously loaded with executable file, one to the buffer allocated to the stack.

+9
source

The compiler saves the first one in the RODATA memory section (read-only data). While the program is still running, the memory still retains its initial value.

The second is stored in the same way as any other array - on the stack. Like any other local variable, it can be overwritten after completion of its scope.

+4
source
  • Formally, in both cases the string "Hello World!" allocated in static memory as a continuous sequence of char , so there is no dynamically allocated memory for recovery or any instance of a class for destruction;
  • Both x will be allocated either in static memory or on the stack, depending on where they are defined. However, the pointer will be initialized to point to the corresponding string "Hello World!" , while the array will be initialized by copying the string literal directly into it.

In theory, the compiler can freely recover the memory of both string literals when there is no way to access them; in practice, the first is unlikely to be restored, since usually static memory remains allocated to the program until it is completed; on the other hand, if the array is allocated on the stack, the second one may not even be allocated at all, since the compiler can use other means to ensure the array is correctly initialized, and the memory of the array will be fixed when it disappears from the sphere.

-1
source

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


All Articles