To allocate memory from the stack or heap for a variable, the size of the variable must be known. C ++ compilers can decide for themselves how they allocate memory, but C ++ made public how they expect C ++ compilers to handle the situation, and therefore C ++ std requires compilers to sell their memory. This happens through the sizeof statement. This operator is fully computed at compile time. The limitation of compilation time for array sizes comes from this requirement.
int arr[10]; std::cout << sizeof(arr) << std::endl
since each variable and type supports sizeof, their sizes must be computed at compile time in C ++. Thus, variable length arrays are not possible in C ++.
There is another very important limitation arising from this requirement. In principle, C ++ compilers could calculate the maximum amount of memory needed for a C ++ program stack if there wasn’t one problem: for recursive functions, you cannot calculate the stack size used by the program, but for everything else, the stack size can be calculated as follows way:
- use sizeof (a) for each variable in the frame stack
- sum the sizes of the variables to get the amount of memory needed for this stack frame
- list all possible frames of the stack and calculate their sizes
- Choose the largest call stack
- select this size as the size of your program stack.
Unfortunately, recursive functions violate the whole scheme. And you need a global analysis of the flow of programs to determine which functions have infinite call stacks. But the limitation for the sizeof size operator is important, or our C ++ programs randomly run out of stack space, causing crashes and instability. And that is unacceptable. Thus, each variable and type supports the size size compile-time statement.
VLA support requires that compilers can generate code in which offsets are usually generated, since the constants for the resulting machine code actually change at run time. Standard compatible C ++ compilers usually do not have the ability to do this. C decided to add this support, and thus C compilers can do this. But in this process, they needed to break the sizeof operator. Compilation sizes can no longer be calculated. VLA support, as stated in the C standard, has big problems:
- you cannot put a vla inside a structure or class
- VLAs are mostly limited to local function scope
These problems have already been resolved in C ++ via std :: vector, which do not have any of these problems.
source share