堆vs数据段与堆栈分配 [英] heap vs data segment vs stack allocation

查看:297
本文介绍了堆vs数据段与堆栈分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看着下面的程序,不知道如何分配内存和原因:

Am looking at the following program and not sure how the memory is allocated and why:

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

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

In the above code, the last one is obviously in the heap. However, as I understand text2 is in data segment of the program and text1 may be on the stack. Or is my assumption wrong? What is the right assumption here? Is this compiler dependent?

感谢

推荐答案

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

这篇关于堆vs数据段与堆栈分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆