Why no variable size array in stack?

后端 未结 7 1179
南方客
南方客 2020-11-27 19:28

I don\'t really understand why I can\'t have a variable size array on the stack, so something like

foo(int n) {
   int a[n];
}

As I underst

相关标签:
7条回答
  • 2020-11-27 20:18

    I'll try to explain this with an example:

    Say you have this function:

    int myFunc() {
       int n = 16;
       int arr[n];
       int k = 1;
    }
    

    When the program runs, it sets the variables in this way onto the stack:

    - n @relative addr 0
    - arr[16] @relative addr 4
    - k @relative addr 64
    TOTAL SIZE: 68 bytes
    

    Let's say I want to resize arr to 4 elements. I'm going to do:

    delete arr;
    arr = new int[4];
    

    Now: if i leave the stack this way, the stack will have holes of unused space. So the most intelligent thing to do is to move all the variables from one place to another in the stack and recompute their positions. But we are missing something: C++ does not set the positions on the fly, it is done only once, when you compile the program. Why? It is straightforward: because there is no real need of having variable size objects onto the stack, and because having them would slow down all the programs when allocating/reallocating stack space.

    This is not the only problem, there is another, even bigger one: When you allocate an array, you decide how much space it will take and the compiler can warn you if you exceed the available space, instead if you let the program allocate variable size arrays on your stack, you are opening breaches in security, since you make all the programs that use this kind of method vulnerable to stack-overflows.

    0 讨论(0)
提交回复
热议问题