Monday, January 28, 2008

Dynamic Memory Allocation on Stack

How to dynamically allocate memory in the stack? Use alloca() is an option:

f()
{
int * i = (int *)alloca(sizeof(int));
}

alloca() allocates on the current stack frame. Anyway it makes no sense to allocate dynamic mem in stack? It does.

If you want to dynamically allocate some memory but do not take the hassle to release it at all exit points. One way to do it is like this.

Another way is to use a smart pointer. However, the second solution is not available in C.

Stack meant for dynamic memory for the CURRENT context. But then we have to make sure the size of the object. If it is a C++ object, then need to use the displacement new method I described before. I believe this is more useful for dynamic array, though dynamic array is supported by C99. For C++, smart pointer is better, or dynamic array. But for C, this is somehow useful.

No comments: