devxlogo

Memory Stack vs. Free Store

Memory Stack vs. Free Store

Question:
When using C++, is it better to use stack or free store memory for data objects of medium to large size? I have multiplatform concerns on the answer. The app will run on Solaris, Linux, and Windows NT.

Answer:
As a rule, whenever you can choose between free store (or “heap,” in C terminology) and stack memory, go with stack memory. It’s much faster?sometime allocating an object on free store allocation is hundreds of times (!) slower than allocating it on the stack. Furthermore, using stack memory, you avoid all the hassles of memory leaks, dangling pointers, null pointer dereferencing, and uninitialized pointers. Your code is much cleaner, simpler, and efficient.

You shouldn’t be concerned about the size of the objects allocated on the stack. All the platforms you mentioned provide a default stack size of at least 1MB per process, and you can configure the compiler to extend this size even further. So unless you’re programming for DOS, stack memory is preferable.

See also  Does It Make Sense to Splurge on a Laptop?
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