in c++ what would happen if we are instantiating an object in global section and the object size is too big?

Viewed 45

Consider the following example:

Foo foo;

int main()
{
    //...
}

What would happen if the size of Foo is too big and allocation fails? Consider a small device with limited memory. Also, what difference would it make if Foo is instantiated within main function?

1 Answers

What would happen if the size of Foo is too big and allocation fails?

The language doesn't specify what would happen. This is what the standard says:

[implimits]

Because computers are finite, C++ implementations are inevitably limited in the size of the programs they can successfully process. Every implementation shall document those limitations where known. This documentation may cite fixed limits where they exist, say how to compute variable limits as a function of available resources, or say that fixed limits do not exist or are unknown.

The limits may constrain quantities that include those described below or others. The bracketed number following each quantity is recommended as the minimum for that quantity. However, these quantities are only guidelines and do not determine compliance.

  • ...
  • Size of an object ([intro.object]) [262 144].

The behaviour may vary across language implementations. You can try it out to discover what happens on your target system. Here is a demo where the operating system raises a segfault: https://godbolt.org/z/PjnfbW

Related