Dynamic array allocation on stack in C

前端 未结 3 1937
南旧
南旧 2020-12-06 07:02

I just did a experiment yesterday, and find something confusing:

#include 

int main()
{
    int j;
    scanf(\"%d\",&j);
    const int i          


        
3条回答
  •  误落风尘
    2020-12-06 07:46

    For some delving into how allocating a variable amount of memory on the stack can work, see this delving into how a compiler can implement the (non-standardized) alloca() function:

    Alloca implementation

    The C99 standard offers Variable Length Arrays ("VLA") with essentially the same functionality; although the memory is reclaimed on a per-scope basis rather than a per-function basis:

    What's the difference between alloca(n) and char x[n]?

    There are some reasons to be hesitant to use either too aggressively with unbounded size. There's no way to check if stack memory is available as you can test for whether heap memory is available via. NULL from malloc(). If your variable length array is too large it will cause a stack overflow and undefined behavior; true for both methods of stack allocation:

    Why is the use of alloca() not considered good practice?

提交回复
热议问题