I think this maybe a really dumb question, but i just want to be clarified. Thanks in advance! I'm not sure if an array of structure declared as a local variable inside a function gets allocated in the stack. Doesn't?
It does; anything you declare without allocating yourself (e.g. by calling malloc
) or declare static (as Fernando says) is allocated on the stack. Structures are just a way of grouping together multiple variables; they still have a fixed size (the total size of their elements, possibly plus some padding), and accessing a struct's field just means pulling the appropriate bytes from somewhere within the struct
It is just like other variable:
void function()
{
struct my_struct a; // in the stack;
struct my_struct *b = malloc(sizeof(struct my_strcut)); // not in the stack;
static struct my_struct c; // not in the stack;
}
Yes, an array declared in a function scope as an auto variable will be allocated from the stack. You want to be judicious when doing so as you can never be certain from the calling context if there will be enough stack space to succeed. Even though Windows by default creates 1MB stacks for threads and Linux creates 8MB stacks by default, you can still have a problem if you create large arrays of structures. In some operating systems the thread stack may be as little as a few kB.
I tend to keep function scope auto variables limited to simple scalar types and put large abstract types and arrays on the heap.
Unless you use malloc() (as @Michael Mrozek said) or declare it with the "static" modifier, it's allocated in the stack.