Char Array VS Char *

2020-07-10 08:09发布

This is a question based on answers from question:

const char myVar* vs. const char myVar[]

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

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

(1) What happens to the "Hello World" string in the first line if I reassign x? Nothing will be pointing to it by that point - would it be destroyed when the scope ended?

(2) Aside from the const-ness, how are the values in the two examples differently stored in memory by the compiler?

标签: c++
3条回答
干净又极端
2楼-- · 2020-07-10 08:29

The compiler stores the first in a section of memory called RODATA (read-only data). As long as the program is still running, the memory still holds its initial value.

The second is stored just like any other array--on the stack. Just like any other local variable, it could be overwritten once its scope ends.

查看更多
Lonely孤独者°
3楼-- · 2020-07-10 08:41

Placing "Hello World!" in your code causes the compiler to include that string in the compiled executable. When the program is executed that string is created in memory before the call to main and, I believe, even before the assembly call to __start (which is when static initializers begin running). The contents of char * x are not allocated using new or malloc, or in the stack frame of main, and therefore cannot be unallocated.

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

查看更多
倾城 Initia
4楼-- · 2020-07-10 08:50
  1. Formally in both cases the "Hello World!" string is allocated in static memory as a contiguous sequence of char, so there is no dynamically allocated memory to reclaim nor any class instance to destroy;
  2. Both xs will be allocated either in static memory or on the stack, depending on where they are defined. However the pointer will be initialized so as to point to the corresponding "Hello World!" string, while the array will be initialized by copying the string literal directly into it.

In theory the compiler is free to reclaim the memory of both string literals when there are no ways to access them; in practice the first one is unlikely to be reclaimed, as usually static memory remains allocated to the program until its termination; on the other hand if the array is allocated on the stack the second one might even not be allocated at all, as the compiler may use other means to ensure the array is properly initialized, and the array memory will be reclaimed when it goes out of scope.

查看更多
登录 后发表回答