0

Below is my simple code snippet.

#include <iostream>
using namespace std;

bool testAllocArray(const unsigned int length)
{
  char array[length];   //--------------------------(1)
  return true;
}

int main(int argc, char** argv)
{
  testAllocArray(1024);     
  return 0;
}

At statement (1), the array seems to be not allocated in heap. I was thinking, it would be allocated in the heap. If it is allocated in the stack, doesn't this lead to crash of some spurious value length as the stack size is pretty much small?

Suresh
  • 27
  • 1
  • 8

1 Answers1

0

It is not allcated on the heap, but on the stack. And when that function returns, it is no longer valid. Same behavior as any other local variable in a function

Stian Skjelstad
  • 2,277
  • 1
  • 9
  • 19
  • Thanks Stian. Isn't this an issue? Because the length could be any value all the way to the max of its limit. – Suresh May 02 '16 at 17:43
  • If length is a very big number, then the application stack can overflow, leading to segmentation fault or udefined behaviour depending on cpu and operating system. But most of todays system can probably have some few megabytes of memory on the stack – Stian Skjelstad May 02 '16 at 17:56