堆栈和堆内存的大小 [英] Size of stack and heap memory

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

问题描述

可能的重复:
栈和堆是什么以及在哪里?

关于c程序中内存布局的基本概念,我的理解是:

With regard to the basic concepts of memory layout in a c program, I understand the that:

  • 该语言使用两种主要的数据结构.
  • 栈是用来存放子程序的局部变量和簿记数据的
  • 堆是用来存放程序动态分配的变量
  • 堆本质上是可变长度的.(在堆栈上不太确定)
  • 通常情况下,编译器/语言有责任在执行之前请求操作系统创建这些数据结构.
  • 创建堆栈/堆的初始大小是多少?谁来决定?
  • 它们是在哪里创建的物理内存?我看到的一般描述为 堆栈在顶级地址中创建,堆在低级地址中创建" 请详细说明此

推荐答案

"栈是在顶级地址和堆中创建的低级地址"请详细说明

"Stack is created in the top-level-address and the heap at the low-level-address" Please elobarate this

这是一个神话.它可能有历史真相的基础.它有时可能会与您在现实生活中看到的事物产生共鸣.但事实并非如此.

This is a myth. It may have a basis in historical truth. It might sometimes resonate with things you see in real life. But it is not literally true.

虽然很容易探索:

#include <stdlib.h>
#include <stdio.h>

void check(int depth) {
    char c;
    char *ptr = malloc(1);
    printf("stack at %p, heap at %p
", &c, ptr);
    if (depth <= 0) return;
    check(depth-1);
}

int main() {
    check(10);
    return 0;
}

在我的机器上我看到:

stack at 0x22ac3b, heap at 0x20010240
stack at 0x22ac0b, heap at 0x200485b0
stack at 0x22abdb, heap at 0x200485c0
stack at 0x22abab, heap at 0x200485d0
stack at 0x22ab7b, heap at 0x200485e0
stack at 0x22ab4b, heap at 0x200485f0
stack at 0x22ab1b, heap at 0x20048600
stack at 0x22aaeb, heap at 0x20048610
stack at 0x22aabb, heap at 0x20048620
stack at 0x22aa8b, heap at 0x20048630
stack at 0x22aa5b, heap at 0x20048640

因此,堆栈向下移动,堆向上移动(正如您可能基于神话所期望的那样),但堆栈的地址较小,并且它们不会相互增长(神话破灭).

So, the stack is going downwards and the heap is going upwards (as you might expect based on the myth), but the stack has the smaller address, and they are not growing toward each other (myth busted).

顺便说一句,我的 check 函数是尾递归的,在某些带有编译器选项的实现中,您可能会看到堆栈根本没有移动.这会告诉您为什么标准没有强制要求所有这些如何工作——如果确实如此,它可能会无意中禁止有用的优化.

Btw, my check function is tail-recursive, and on some implementations with some compiler options you might see the stack not moving at all. Which tells you something about why the standard doesn't mandate how all this works -- if it did it might inadvertently forbid useful optimizations.

这篇关于堆栈和堆内存的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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