About C/C++ stack allocation

前端 未结 7 695
一个人的身影
一个人的身影 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:07

    In C and C++, there are two types of memory allocation 'automatic', where the object is created for the lifetime of a function call, and 'dynamic', where some memory is allocated by a function provided by the runtime.

    In the vast majority of runtime implementations, automatic objects are allocated using a contiguous stack provided by the operating system when the thread is created. The stack typically starts at a high valued address, and is decremented by the size of the object. Dynamic allocations (malloc in C, new in C++) use some other memory requested from the operating system. As the OS knows about the addresses the stack is using, it doesn't allocate the same addresses to the dynamic requests. As the dynamic area is not ordered, it is often called the heap.

    So 'stack' allocation doesn't malloc/free. Automatic objects in C++ call the constructor and destructor, but not new or delete, as new and delete also have the code to manage dynamic memory.

提交回复
热议问题