堆、数据段、堆栈分配
我正在查看以下程序,不确定内存是如何分配的以及为什么:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,你是对的,在大多数系统上:
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 beconst 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