Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to declare large struct objects in the static-global area?

Tags:

c

memory

struct

I'm thinking of creating a global static struct, like so:

typedef struct {
    Thing things[1024];
} MyBigStruct;

static MyBigStruct s;

Is there a reason, memory-wise or other, why not to put large struct objects in the "static-globals area"? Is there a limit to this area? Should I declare this with malloc in the heap?

Please refer not to coding practices against global variables, but only to the technical aspect.

like image 545
Aviv Cohn Avatar asked Oct 15 '25 18:10

Aviv Cohn


1 Answers

Variables declared in globally typically live in the data segment area of memory. This area doesn't have the same restrictions on size that the stack has (aside from physically available memory), so it's perfectly fine to declare large variables globally.

Depending on just how big these variables are, you'll probably get a slight runtime gain over using dynamic allocation as the space for this variable is set aside at program startup as opposed to the runtime cost of allocating this memory from the heap.

like image 136
dbush Avatar answered Oct 17 '25 08:10

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!