About C/C++ stack allocation

前端 未结 7 685
一个人的身影
一个人的身影 2020-12-15 12:44

While studying C++ (and C) I had some particular doubts regarding the working of stack allocation, that I can\'t find a solution to:

  1. Does stack allocation c

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 13:09

    Stack allocation doesn't use anything like malloc/free. It uses a piece of memory called program stack which is just a contiguous segment of memory.

    There's a special register that stores the top of the stack. When a new object is created on stack the top is raised thus increasing the stack, when an object is deallocated (goes out of scope) the top is lowered thus decreasing the stack.

    If you try to allocate a too large object on stack or go too deep into recursion the top will outgrow the maximum allowed size of the stack and this is called stack overflow.

    Note: actual direction of stack growth (increasing or decreasing addresses) will vary by system, but general idea is the same regardless of actual direction.

提交回复
热议问题