How to deallocate variables on the stack?

前端 未结 6 1712
一向
一向 2021-01-29 14:15

Is there a way to deallocate variables and/or objects created on the stack? I am specifically talking about the stack not the heap.

I do not want to debate whether this

6条回答
  •  孤街浪徒
    2021-01-29 15:22

    The question is meaningless. Generally, stack for thread is allocated (memory reserved and partially committed) on process heap when thread is created. And dealocated when thread (normally) exits . It has a fixed maximum size (reserved memory) during run-time and "grows" by committing more memory from reserved pool. There is no actual memory allocation happens when function call uses stack - the stack space function uses (for its local variables) is a region of pre-allocated and committed memory. You cannot de-allocate it.

    Imagine, you allocated 100 bytes on heap at address addr, pass pointer to addr+0x40 and size 0x10 to function for it to use internally. Function can create some variables (objects) at this address, total size no more than 16 bytes, using, say, placement new. It can (and, generally, should) destroy objects by calling destructors explicitly. But it has no business deallocating any memory - pointer passed to it does not even point to the beginning of allocated region... And that's, very simplified, how stack works - function gets portion of pre-allocated memory for its local variables, it calls constructors at this memory, then upon exit it calls destructors. But it does not allocate or deallocate any stack space. Attempt to do it will cause access violation (segmentation fault).

提交回复
热议问题