Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does object's memory profile need to be known at compile-time for stack placement?

It seems to be a well-accepted fact that if you instantiate an object in a language like C++, it is only eligible for stack placement (as opposed to heap allocation) if the size of the object is known at compile time. For example an array of fixed size can go on the stack but the elements of a vector will be placed on the heap since the final size is unknown during compilation.

Why is this the case? Why can't stack space be dynamically allocated during runtime by moving the stack pointer?

EDIT: For clarification, here's an example: in the middle of a function, you compute a non-const integer. If you want to create an array of this size, the allocation must be done on the heap because the size of the array is not known at compile-time. But why can't you just put the array at the top of the stack when it is created?

like image 528
rampatowl Avatar asked Nov 15 '25 14:11

rampatowl


2 Answers

Consider this code:

void extend(std::vector<int>& v, int val) {
    int w = abs(val);
    v.push(w)
}

std::vector<int> v(10);
extend(v, 3);

If the content of v is on stack, it will not be continuous since there's other stuff between v[9] and the newly pushed v[10]. Worse, if the operation is forced, then v[10] will almost surely overwrite something.

like image 74
iBug Avatar answered Nov 18 '25 06:11

iBug


You can do it with the function alloca() for gcc, and the functions _alloca() and _malloca() for Microsoft compilers.

This looks as follows:

void allocatesArray(int i)
{
    char *ray = reinterpret_cast<char*>(alloca(i));
    // 'i' bytes of memory allocated, returns void * 

    ray[0] = 'a';
    // space freed, pointer invalidated
}

Mind that it is not considered as a very good practice because of undefined behavior in the case of a stack overflow.

like image 43
Kostas Avatar answered Nov 18 '25 06:11

Kostas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!