To my understandings, dynamic allocation is preferred to declaring local variables when
But AFAIK global variables are allocated on the data segment, which is also fairly large compared to the stack.
Suppose I have a large variable whose lifetime will be throughout the entire program and the concerns are only its size. Will there be still any disadvantages in declaring it globally instead of calling malloc
?
People often warn that global variables are evil because they make the code complex and unclear, but I don't think I should care for this because in my case the file scope is small.
The term "global variable" isn't very helpful, because it actually means something in the global namespace accessible everywhere. Such variables are definitely bad and should always be avoided.
Instead we can declare a variable at file scope without making it global, by adding static
(internal linkage instead of external linkage). Once that is done, the whole "globals are bad" discussion is irrelevant - the variable is now only accessible from the translation unit where it was declared.
Another valid concern against having a static int array[n];
at file scope is thread-safety. Such an array might have to be protected against race conditions if used by more than one thread. But turning it dynamic won't solve that problem: either you need to access the whole array from multiple threads, in which case you need protection anyway. Or you only need to access different parts of the array from multiple threads, in case you won't need protection. Regardless of how it was allocated.
With these things in mind, no there is nothing wrong of having a static int array[n];
declared at file scope and allocated at .data
/.bss
(if it will fit). In fact there are many big advantages of doing so compared to dynamic allocation: no fragmentation, no allocation overhead, no memory leaks.