【问题标题】:heap vs data segment vs stack allocation堆与数据段与堆栈分配
【发布时间】:2011-09-06 11:37:41
【问题描述】:

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

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

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

【问题讨论】:

  • +1 : 非常有趣的问题
  • 你明白指针和它所指向的数据的区别吗?
  • 是的,n0rd,但是这个让我印象深刻,因为它似乎有多种可能的选择..
  • 这是一个很好的面试问题:)
  • text1text2text 本身就在堆栈中。但是"..."s 在文本段中。从malloc 获得的分配内存在堆中。

标签: c++ heap-memory stack-memory


【解决方案1】:
// 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 );

【讨论】:

  • 如果你抛弃text2 的常量并尝试修改它会发生什么?这是段错误吗?
  • 是的。这会导致段错误。
  • @DrewNoakes 这是未定义的行为。这可能是段错误,但你不能指望它。
【解决方案2】:

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

text1是栈上可写变量数组(必须是可写数组)

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

text 将在堆上

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 1970-01-01
    • 2011-05-28
    • 2013-10-20
    • 2014-06-23
    • 2017-02-23
    • 2010-10-03
    • 2023-03-03
    相关资源
    最近更新 更多