Aviv Cohn
Aviv Cohn

Reputation: 17233

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

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.

Upvotes: 4

Views: 608

Answers (2)

ryyker
ryyker

Reputation: 23226

Is there a reason, memory-wise or other, why not to put large struct objects in the "static-globals area"?

No. It is perfectly fine to use globals in the way you have described, and even advantageous in some ways. (eg. in terms of run-time speed over dynamic allocation.
However, although not size related, there are other disadvantages to using global variables. For example globals can be problematic when using multiple threads. Any function in your code that access a global is no longer re-entrant, one of the tenets of a thread safe function. If multi-threading is included in your application, then extra precautions are needed to share global objects between threads.

Is there a limit to this area? Should I declare this with malloc in the heap?_

The data section of memory [is] for global and static data ..., suggesting its size is limited only by the amount of physical memory available on your system. ( A more detailed discussion on physical memory limits can be found here. )

Upvotes: 3

dbush
dbush

Reputation: 224342

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.

Upvotes: 4

Related Questions