tags:

views:

113

answers:

4

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?

+7  A: 

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

Michael Mrozek
+1, but of course, `new` is c++
Stephen
@Stephen Ah, yes. I have a bad habit of translating "In C" to "In C or C++, your choice" automatically as I read
Michael Mrozek
The stack and the heap are implementation details aren't they? I'm not even sure the C standard mentions the word "stack".
dreamlax
@Phong I have no idea what global variable you're referring to; he says "declared as a local variable inside a function"
Michael Mrozek
Also worth noting is you can explicitly allocate something on the stack; c.f. alloca.
jer
You forgot about static allocation. Variables in global scope and variables with "static" qualifier.
Juliano
@Michael: I was speaking about the static local variable. (mistake the vocabulary). I removed the -1 since it is corrected.
Phong
A: 

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;

}
Phong
+1  A: 

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.

Amardeep
+1  A: 

Unless you use malloc() (as @Michael Mrozek said) or declare it with the "static" modifier, it's allocated in the stack.

Fernando