C++ 堆与数据段与堆栈分配

C++ 堆与数据段与堆栈分配,c++,stack,heap,C++,Stack,Heap,我正在查看以下程序,不确定内存是如何分配的,以及原因: void function() { char text1[] = "SomeText"; const char* text2 = "Some Text"; char *text = (char*) malloc(strlen("Some Text") + 1 ); } 在上面的代码中,最后一个显然在堆中。但是,据我所知,text2位于程序的数据段中,tex

我正在查看以下程序,不确定内存是如何分配的,以及原因:

void function() {
    char text1[] = "SomeText";
    const char* text2 = "Some Text";
    char *text = (char*) malloc(strlen("Some Text") + 1 );
}

在上面的代码中,最后一个显然在堆中。但是,据我所知,
text2
位于程序的数据段中,
text1
可能位于堆栈上。还是我的假设错了?这里的正确假设是什么?此编译器依赖于吗?

是的,在大多数系统上,您是对的:

// Array allocated on the stack and initialized with "SomeText" string.
// It has automatic storage duration. You shouldn't care about freeing memory.
char text1[] = "SomeText"; 

// Pointer to the constant string "Some Text".
// It has static storage duration. You shouldn't care about freeing memory.
// Note that it should be "a pointer to const".
// In this case you'll be protected from accidential changing of 
// the constant data (changing constant object leads to UB).
const char* text2 = "Some Text";

// malloc will allocate memory on the heap. 
// It has dynamic storage duration. 
// You should call "free" in the end to avoid memory leak.
char *text = (char*) malloc(strlen("Some Text") + 1 );
text1
将是堆栈上的可写变量数组(要求是可写数组)

text2
实际上必须是
const char*
,是的,它将指向可执行文件的文本段(但这可能会随着可执行文件格式的不同而变化)


text
将在堆上

+1:非常有趣的问题你理解指针和它指向的数据之间的区别吗?是的,不,但是这一个让我印象深刻,因为它似乎有多种可能的选择。这是一个很好的面试问题:)
text1
text2
text
本身就在堆栈上。但是,
“…”
s在文本段中。从
malloc
获得的已分配内存在堆中。如果从
text2
中丢弃常量并尝试修改它,会发生什么?这是一个错误吗?是的。这将导致segfault。@DrewNoakes这是未定义的行为。这可能是一个错误,但你不能指望它。