On Wednesday, 16 August 2017 at 07:39:01 UTC, Suliman wrote:
On the heap, unless you are allocating it via e.g. alloca.

If
struct MyStruct
{
 int x;
 int y;
}

MyStruct mystruct;

is located on stack, why:

MyStruct [] mystructs;

should located on heap?

MyStruct[] is actually a struct similar to this:

struct MyStruct[] {
    MyStruct* ptr;
    size_t length;
}

That struct is placed on the stack, but the data it points to, via the ptr field, is heap allocated.

One explanation of why is that the compiler doesn't know how many elements are in the array, and that that number may change. If it was stack-allocated and a new element was added to the array, everything on the stack would have to be moved.

If the compiler does know the number of elements, it can allocate the array on the stack (theoretically, this could be done as an optimization, but in practice I don't think it is). You can give the compiler this information:

MyStruct[10] mystructs;

This will allocate 10 MyStructs (80 bytes) on the stack, and if you change 10 to a large number, will give a stack overflow.

--
  Biotronic

Reply via email to