gpt4 book ai didi

c++ - 堆与数据段与堆栈分配

转载 作者:IT老高 更新时间:2023-10-28 22:26:53 25 4
gpt4 key购买 nike

正在查看以下程序,但不确定内存是如何分配的以及为什么:

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 );

关于c++ - 堆与数据段与堆栈分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6204834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com