堆、数据段、堆栈分配

发布于 2024-11-11 16:53:27 字数 329 浏览 3 评论 0原文

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

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

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

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

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

In the above code, the last one is obviously in the heap. However, as I understand text2 is in the 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

二智少女 2024-11-18 16:53:27
// 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 );
// 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 );
呆橘 2024-11-18 16:53:27

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

text1将是堆栈上的可写变量数组(它必须是可写数组)

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

text 将位于堆上

Yes you are right, on most systems:

text1 will be a writable variable array on stack (it is required to be a writable array)

text2 has to be const char* actually, and yes, it will point to a text segment of the executable (but that might change across executable formats)

text will be on heap

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文