4

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.

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • 2
    How could there *not* be a limit to this area? – Scott Hunter Apr 26 '19 at 16:06
  • In general, global data structures are a bad code smell. They make for brittle programs that can't parallelize. The exception is if this is truly a static constant: its value never changes. The rest of your question has no general answer. There are always limits as @ScottHunter said. They're totally environment-specific. A small embedded controller will be different from a high capacity server. And even for a given machine, the OS and compiler both get a vote. – Gene Apr 26 '19 at 17:54

2 Answers2

4

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
3

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. )

ryyker
  • 22,849
  • 3
  • 43
  • 87