Auto / Static Memory Allocation

Maybe a naive question, but ...

Confirm or reject:

The existence of memory for objects / variables of automatic and static storage time is determined by compilation time, and there is absolutely no likelihood that the program will fail at run time because there is not enough memory for the automatic object.

Naturally, when the constructor of an automatic object performs dynamic distributions, and such a distribution fails, we consider this a failure in dynamic allocation, and not automatic.

+4
source share
6 answers

Two words: Stack overflow .: P

+13
source

Automatic allocation can certainly be unsuccessful - this is commonly called stack overflow. You see this quite often when someone tries to have a large array as a local variable. Unlimited (or unlimited) recursion can also cause this.

What you really cannot do in a platform-independent way is to detect an automatic distribution failure and handle it.

+14
source

On systems with overcommit (for example, Linux in the default configuration), even for objects with static storage durations, runtime failures can occur. When the program starts, these objects will exist either with zero pages with copy to write (if they were not initialized), or with copy-to-write mappings of the executable file to disk. The first time you try to write them, a page error will occur, and the kernel will make a local, modifiable copy for your process. If the kernel was careless and did not reserve as much memory as was fixed in this process, this may fail, and the result will be a terrible OOM-killer.

No reliable system has this problem, and Linux behavior can be fixed:

echo "2" > /proc/sys/vm/overcommit_memory 
+4
source

Not true. Automatic allocation can cause a stack overflow, which causes an instant termination of the process on most architectures / platforms that I know of.

In addition, it is possible that the program cannot allocate enough space for your static variables from the base platform, in which case the program will still fail, but it will fail before main is called.

+2
source

A simple counterexample:

 #include <string.h> int main() { int huge[0x1FFFFFFF]; // Specific size doesn't matter; // it just has to be bigger than the stack. memset(huge, 0, sizeof(huge) / sizeof(int)); return 0; } 
0
source

Example:

 #include <iostream> using namespace std; class A { public: A() { p = new int[0xFFFFFFFF]; } private: int* p; }; static A g_a; int main() { cout << "Why do I never get called?" << endl; } 
-1
source

All Articles