devxlogo

Memory allocation at compile time

Memory allocation at compile time

Question:
Consider the following piece of code:

#include  /* C++ String class */static String s(“hello”);main() {  // … your code  s += ” world”; // …}
Question: String class uses the new operator to allocate space for the char string argument in the constructor. Where exactly is space allocated for the static string s? If new allocates only heap memory, then s is on the heap. This implies that heap memory can be allocated at compile time. Correct?

Answer:
Nice try but no cigar.

Static initialization has two phases: a static phase that is resolvedat compile time, and a dynamic phase that happens at run time.

At the static phase, all statics and globals that are initialized withconstant expressions are evaluated; all other things (calls to constructors, initialization with calls to functions including operator new, etc.) are dealt with at run time. These can be initialized either before the callto main or sometime later before any function in the module(file) in whichthey are defined is called.

So at compile time, the compiler only generates code to call the constructorto string at the appropriate place.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist