Run-Time Check Failure #4 – Stack area around _alloca memory reserved by this function is corrupted?

  alloca, c++, runtime-error, stack
#include <iostream>
#include <malloc.h>

void print_vals(int n)
{
    int *arr = (int *)alloca(n);

    for (int i = 0; i < n; i++)
        arr[i] = i;

    for (int i = 0; i < n; i++)
        std::cout << arr[i] << ' ';

    std::cout << 'n';
}

int main()
{
    print_vals(5);
    print_vals(10);
}

When I run this code, I get this error per call:

Run-Time Check Failure #4 - Stack area around _alloca memory reserved by this function is corrupted

enter image description here
I’m using Visual C++ 2019, both stdc++14 and stdc++17 produce the same error.

What’s wrong with this code?

Source: Windows Questions C++

LEAVE A COMMENT