Stack vs Heap: Understanding Memory Allocation in Programming

Seyyid Yiğit
Huawei Developers
Published in
14 min readOct 31, 2023
Created Bing AI

Introduction

Hey there, think you’re creating a space for your ideas and plans to come together — that’s similar to memory allocation in the programming world! 🧠 It’s like a house party for data and tasks where you assign rooms (or memory space) for each one. 🎉 This is critical because it has a direct impact on how effectively your software operates, how efficient it is, and how reliable it becomes. 💯

There are several methods for organizing this party, depending on the type of guests (data and tasks) you have. In this article, we’ll take a look at two of the most common rooms: the stack and heap memory. 🥂Stay with me as we explore these exciting programming memory allocation concepts!

😔

Memory Segments

Think about a memory segment to be a friendly stretch of land in your computer’s memory world🌎, each section with its own distinct role in assisting a program to do its thing. Imagine yourself to have four primary plots of land, each of which properly tucks away data and orders for the program. 📦 Global, code, stack, and heap plots represent the heart and soul of each program’s memory architecture. ❤️

Memory Structure

Let’s talk about all those sections of memory where your application stores its data, similar to partitions in a large suitcase! 🧳

  • First, we have the global memory segment. You can think about this as a special area where your software maintains elements that are always present, such as the sun in the sky! ☀️So, if you have variables or constants that you use everywhere and need to keep around for the duration of your program’s execution, they have right here in this global memory section. 🌐 It’s a highly accessible location since these variables and constants may be reached from anywhere in your program.
  • Next up, we’ve got the code memory segment. It’s almost like the rulebook for the program! 📚 This is where how-to-dos — the actual activities your program does — are located, such as functions, methods, loops, statements, and so on. 💻 It’s like a read-only recipe book, because once it’s written, we never go back and change it in the middle of cooking our program. 🍳
  • Then there’s the stack memory section, which is a nice little area. It functions as a notepad for your program to write down all the local variables and parameters that are only relevant when it is task-specific (that’s a function or class). 📝Just like the notes you while on a call and then throw away when you’re finished. 🗑 It also keeps track of all the tasks (functions) your program needs to do in what order, kind of like a to-do list. 📋 It’s a write-down-and-push-aside type of place and it always takes care of the last thing added first, like finishing the topmost task on your to-do list. ✅
  • Finally, we have the heap memory segment. This is a brilliant little location for variables and objects that spring to life using pointers or references as your program runs. 🔥 They’re like surprise guests who can arrive and leave at any time during the party! 🎉 They survive until they’re no longer needed. 💔 The heap is a free spirit and doesn’t depend on any particular order but organizes the memory space in a hierarchy like a family tree. 🌲

Stack Memory

Alright, let’s break down stack memory in a simple and friendly way. Imagine it like a storage cupboard where we keep temporary items we’ll need while we’re working on a project. 🛠️

Stack Memory Working Principle
  • Linear structure: Picture the cupboard’s shelves lined up in a row. This is similar to stack memory’s linear structure. 📚 Each shelf is reserved for one item, like a memory cell or slot in the stack. The handyman, or ‘stack pointer’, is always keeping an eye on the topmost shelf of the cupboard. 👀 If we add something, it goes onto his current shelf — he moves up a shelf. ⬆️ When we remove an item, it comes off his current shelf, and he moves down. ⬇️
  • Temporary storage: This cupboard is used to hold items just for a while. For instance, when we’re working on a task (like a function in a program), we put the materials we need and the task instructions in the cupboard. 📦 When we’re all done, we empty out those items. 🗑️ Plus, we keep a reminder of where we need to get back to after the task is done — that’s like the return address. 🏠
  • Automatic allocation and deallocation: The good news is, that our handyman takes care of putting items in the cupboard and taking them out. No need for us to worry about giving any detailed instructions or accidentally leaving something behind. 😌 This makes everything smoother and avoids any problems! 😊
  • Faster access: Our cupboard is really close to our workspace, so grabbing what we need is quick and easy. 🏃‍♂️ This is similar to how accessing items in stack memory is faster than accessing stuff in a distant storage room (or heap memory). 🚗
  • Limited size: As neat as our cupboard is, it has its limitations. The amount of space is fixed and depends on several aspects like the dimensions of the place, the kind of shelves we’re using, etc. 📏 Sometimes we find ourselves trying to put too much in there (kilobytes to megabytes in code talk!), and if that happens, uh oh, we’ve got a ‘stack overflow’. 😱 This means there’s no more room, and we need to stop and fix this issue before we can continue. 🔧

So, there you have it! Stack memory in a nutshell — or a storage cupboard! Isn’t code exciting? 🎉

Created FireFly AI

Heap Memory

Let’s take a joy ride into the world of heap memory, shall we? 🚗 It’s a type of memory segment in our computing world that works like a closet for your dynamic data and objects; a place for them to hang out while a program runs. 🧥

  • Tree-like structure: The way heap memory is designed is much like a family tree. 🌲 Picture blocks, serving as the roots and branches, layered atop each other. Each block can hoard varying amounts of data or objects — much like a mini storage unit. 📦 Now, to keep everything in check, we have a trusty pal, the heap pointer (HP). 👋 It’s a register that keeps an eye on the root block. 👁️ Each block earns a unique address or identifier when it’s brought onto the heap, captured by a pointer or reference variable. 🔗 And when it’s no longer needed? It’s marked free, ready, and waiting for the next round of use. 🆓
  • Power of stay: Heap memory loves long-term relationships. 💘 It’s where you store dynamic data and objects that have a long date with the running program. 📆 If an object is pushed into existence using the new operator or keyword, it sets up camp on the heap until you decide otherwise with the delete operator or keyword, or until the program calls it a day. ⛺
  • DIY allocation: Here’s where you, the programmer, step in. Heap memory is your playground, you manually add and remove blocks. 🎮 To make this happen, you’d use commands like new, delete, malloc, free, and so forth. 💻 It’s more hands-on, allowing you to manage your memory space. 👐 It’s a bit more challenging and needs delicate handling to work around potential memory leaks or errors, but hey, who doesn’t love a challenge? 😎
  • Slower stride: The one minor flaw of heap memory — it’s slower than stack memory. 🐢 Imagine creating or destroying a block on the heap like a complicated dance move — it requires more steps. 💃 Also, think of heap memory as the quiet cabin in the corner of the woods, far from the main house; it takes longer to access because it’s physically distant from the CPU. 🏡
  • Size matters: Heap memory is the big sibling among memory types. 🐘 It takes up a substantial part of the memory space in a program, swinging in the ranges from megabytes to gigabytes. 💾 It’s like a garden — various things such as the operating system, hardware, and the program itself decide its extent. 🌻 But beware, if the heap becomes too full or pushes the limit, it results in an OutOfMemoryException error, causing your program to slow down or even crash. 😱 But hey, with the right amount of care, we can avoid it. Every garden need tending, right? 🌷
Created FireFly AI

Stack vs Heap, Friend to Friend

Alright, let’s talk about stack and heap memory, two siblings in the programming world with their own unique set of skills. 🌟 These two acts differently when storing your data and instructions in your code and depending on what you’re dealing with and how you’re using it, one might be a better fit for your needs. 🤔

Stack & Heap

Why you might choose stack memory:

  1. Stack memory is pretty straightforward to use and keep in check, simply because it doesn’t ask you to manually allot or free up your memory so… that’s one less thing to worry about! 😌
  2. When it comes to speed, stack memory outruns heap memory, just needing one simple action to add or remove an item. Now that’s quick! 🏃‍♂️
  3. Stack memory is a bit of a space-saver too. It doesn’t lead to space waste or leaving gaps, so it’s super-efficient! 💯

But stack memory is not all sunshine and rainbows: 🌈

  1. Stack memory is pretty much a stickler when it comes to size and scope; it can only hold temporary data or instructions that are confined to a particular function or class. 📏
  2. It’s not so good with handling dynamic stuff like data and objects because it’s not able to allot or free up memory space on the go. 🙅‍♂️
  3. Also, stack memory might throw a spanner in the works and cause stack overflow errors if it gets too stuffed and exceeds its limit. 😱

Let’s pivot over to the advantages heap memory offers: 🔀

  1. Heap memory prides itself on being flexible and resourceful; it can easily deal with dynamic data and elements that are not just local, but rather, accessible across your entire program. 🌐
  2. It’s pretty powerful in handling dynamic data and objects, able to add or get rid of memory space in real-time. 💪
  3. Plus, heap memory has quite a bit of elbow room compared to stack memory because it snags a major chunk of the available memory in your program. 🐘

Now the flip side of heap memory: 🙃

  1. Heap memory can be a bit of a tough cookie to handle and keep orderly, mainly because it asks for your help in assigning and releasing the memory. 👐
  2. It takes its sweet time with access speed, needing more operations than stack memory when it comes to creating or getting rid of a node or block. 🐌
  3. And don’t forget, if heap memory oversteps its bounds too much, it could cause an OutOfMemoryException error. 😱

That’s all there is to it. Each offers advantages and disadvantages, allowing you to choose what is ideal for your coding career! 🚀

Examples of when to use stack and heap memory in programming

Hey there coder! 😊 So, you’re wondering when you should use the stack and heap memory in your programs? Great question! 🙌 Wouldn’t you know it, it hinges on a handful of aspects — the kind of data you’re dealing with, its scope, its lifespan, its size, how the program performs, and so on. However, here are some simple rules of thumb: 👍

Cheers to the stack memory when: 🥂

  • Your data or command is just passing through, making a brief appearance in a specific function or class. 👋
  • The size and type of the data or command are set in stone and known upfront before the program runs. 🗿
  • You don’t plan on changing the data or command midway through the running of the program. 🚫
  • Keeping the program humming along speedily and efficiently is critical to you. 🚀

Raise a glass to heap memory when: 🍾

  • Your data or object likes to live on the edge, changing in the moment and making itself available globally in your program. 🌎
  • The size and type of the data or object are as unpredictable as the weather, not known until the program gets going. 🌦️
  • You might need to tinker with the data or object while the show — I mean, program — is on the road. 🔧
  • You value the ability to change things up and want your program to be adaptable and multifaceted. 💎

Example Code and Exception

Yes, folks, we will look at the example code below. 😊 This example code has a Person class as well as a Main function. Local variables are stored on the stack, and Person objects in Heap. 🧠 Actually, that Person object memory address is stored in the stack. 📝 Then, using this memory address, access data in the heap. 🔗

 class Program
{
public class Person
{
public string name;

public Person(string name)
{
this.name = name;
}
}


public static void Main(string[] args)
{
// Stored on the Stack (local variables)
string name = "John";
string copyName = name;

// Stored on the Heap (Created obj with new keyword)
Person person = new Person(name);
Person person2 = person;

Console.WriteLine("Person Name:" + person.name);
Console.WriteLine("Person2 Name:" + person2.name + "\n");
Console.WriteLine("Local Name: " + name);
Console.WriteLine("Copy Local Name: " + copyName);

Console.WriteLine("\n----After Changes---- \n");

//If change person name, then person2 name change.
//Because they are stored heap with same referance.
person.name = "Frank";
Console.WriteLine("Person Name:" + person.name);
Console.WriteLine("Person2 Name:" + person2.name + "\n");

//If change local name variable, then copryName not changed.
//Because they are stored stack and two different address in stack.
name = "Frank";
Console.WriteLine("Local Name: " + name);
Console.WriteLine("Copy Local Name: " + copyName);

Console.ReadKey();
}

}
Stack and Heap Memory Diagram — Example Code Output

StackOverFlowException

Each time you call up a function or method, it’s like telling your program to stuff its data inside that box. 📦 And when the function completes its work, the program takes that data out. 🗑️ But if there’s no more room left in our box to either store or remove anything, we get this unwanted party crasher — the stackoverflow exception. 😱

One of the usual reasons behind this exception is a never-ending recursion — think of a function that keeps calling itself forever without any exit. 🔄 This function keeps piling its own data on our box until it basically explodes! 💥 For instance, check out this chunk of C# code: 💻

 class Program
{

public static void Main(string[] args)
{
// Stored on the Stack
string name = "John";

try
{
// Stored on the Stack
WriteName(name);

}catch (StackOverflowException e)
{
Console.WriteLine(e.ToString());
}

}


public static void WriteName(string name)
{
WriteName(name);
}

}
StackOverFlowException — Code Output

To prevent a stackoverflow error, you should write more intelligently. 🧠 You can implement fail-safes to raise an alarm if your program’s stack becomes overcrowded. 🔔 Consider adding an exit condition to any recursive loop or trading recursion. 🛑

Loop

OutOfMemoryException

The OutOfMemoryException is an exception that is thrown when there is not enough memory to continue the execution of a program. This exception does not always mean that the physical memory is full, but sometimes it means that the available memory space is fragmented or insufficient for the allocation request. For instance, check out this chunk of C# code: 💻

class Program
{
static void Main(string[] args)
{
try
{
List<int[]> list = new List<int[]>();
while (true)
{
list.Add(new int[1024 * 1024 * 1024]); // Allocate 4GB of ints repeatedly
}
}
catch (OutOfMemoryException ex)
{
Console.WriteLine(ex.ToString());
}
}
}
OutOfMemoryException — Code Output

To avoid or handle this exception, it is recommended to write code that detects and prevents a memory overflow situation, such as using a counter or a condition to terminate a recursive loop or using an iterative approach instead of a recursive one.

Conclusion

Getting the hang of stack and heap memory can really power up your coding game! 💪 Think of stack memory like a notepad you use for scribbling down quick notes — it’s super-fast but doesn’t have a ton of space. 📝 On the other hand, heap memory is like a big ol’ filing cabinet where you can stow away larger, dynamic data — though you’ll need to keep it in order and it’s a bit slower. 🗄️

Whether you reach for your notepad or filing cabinet depends on the kind of data you’re dealing with — its type, scope, lifespan, and size. 🤔

In the world of C#, your classes, which are reference types, hang out on the heap, while you structs and primitives, the value types, chill in the stack. 😎 Being savvy about this can help you manage memory like a pro. 👏

By embracing these ideas, your software will not only become sturdy but also efficient. 🚀 I hope this cheerful lil’ rundown helps you sink your teeth into the thrilling saga of stack vs heap memory in programming. No programming drama would be complete without it! 🎭

References

--

--

Seyyid Yiğit
Huawei Developers

I’m a software engineer at Huawei. I love AI, fitness, gaming and sharing my projects and tips with you. Curious? Let’s learn together!