avatarAve K

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3749

Abstract

l5sdjeSgbQ.png"><figcaption>Figure 3: And similarly when func1() exits, the stack with int a & b has be reclaimed.</figcaption></figure><p id="8e13">The stack is much faster than the heap. This is due the localization and optimization in modern CPUs. This is because the data on the stack is contiguous and when the CPU fetches the data of a specific address, it also pulls in the neighboring address into the CPU’s cache because it’s very likely that the program will need the neighboring data as well.</p><p id="d027">Finally the stack is a fixed size that is determined by the OS at runtime when the thread is created. When the stack runs out of memory, it will result in a <i>stack overflow</i> exception, this is usually caused by calling nested functions too many times.</p><h1 id="ab89">What is the heap</h1><p id="484c">The head is global and is shared by all threads. This means there must be some sort of synchronization if multiple threads are accessing the same data. <i>Also, allocation and deallocation doesn’t follow any fixed pattern and can occur ad-hocly. (Note: This applies mainly for languages like c++ where developers can control allocating and deallocating memory freely. But even with languages like JAVA, the same concept applies to the garbage collector. When you exit from a function, it’s not guaranteed the garbage collector will run and consequently the memory allocated in the heap from the function call is not freed on function exit. Eventual the garbage collector will run and reclaim the memory but it’s determined by the language runtime)</i></p><p id="8d88">To help visualize heap allocation, see the below c++ code that explicitly allocated and deallocates memory on the heap to illustrate the global nature of the heap. <i>It also illustrates how memory leaks can occur when working with languages that allows manual heap allocation.</i></p><div id="59e0"><pre><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">func3</span><span class="hljs-params">()</span> </span>{ <span class="hljs-type">int</span> e = <span class="hljs-number">4</span>; <span class="hljs-type">int</span> f = <span class="hljs-number">5</span>; }

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">func2</span><span class="hljs-params">()</span> </span>{ <span class="hljs-type">int</span>* c = <span class="hljs-keyword">new</span> <span class="hljs-built_in">int</span>(<span class="hljs-number">2</span>); <span class="hljs-type">int</span>* d = <span class="hljs-keyword">new</span> <span class="hljs-built_in">int</span>(<span class="hljs-number">3</span>);

<span class="hljs-keyword">delete</span> c; }

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">func1</span><span class="hljs-params">(<span class="hljs-type">int</span>** a)</span> </span>{ a = <span class="hljs-keyword">new</span> <span class="hljs-built_in">int</span>(<span class="hljs-number">0</span>); <span class="hljs-type">int</span> b = <span class="hljs-keyword">new</span> <span class="hljs-built_in">int</span>(<span class="hljs-number">1</span>);

<span class="hljs-built_in">func2</span>();

<span class="hljs-keyword">delete</span> b; }

<span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{ <span class="hljs-type">int</span>* a; <span class="hljs-built_in">func1</span>(&a); <span class="hljs-built_in">func3</span>(); <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>; }</pre></div><figure id="ef31"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*3ebHJK-g04

Options

xRn2qj5CMq2A.png"><figcaption>Figure 4: At line 8 all integers up to func2() execution has been allocated on the heap. Notice before exiting from func2() allocation needs to be cleaned up (delete c)</figcaption></figure><figure id="48f5"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*fwbo05aHBMsx6t4XV2BhAg.png"><figcaption>Figure 5: Manually deleting allocation on the heap before exiting from func2(). Notice not deleting d will result in memory leak</figcaption></figure><figure id="4c60"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*GW7P2-41LB4Z-qyXzIoOFg.png"><figcaption>Figure 6: Even after returning from func1() and still have access to int a because the scope of the heap is global</figcaption></figure><p id="180f">Note: There are many memory leaks in the above code that is not conveyed in the visualization. Any allocation on the heap must be cleaned up, either manually (e.g. via delete) or automated (via smart pointers).</p><p id="062f">The heap is much slower than the stack because there is much more complex bookkeeping involved in allocating and deallocating memory (especially in multithreaded environments). Since the heap is a global resource there is a performance hit in each allocation and deallocation because of requiring synchronization with “all” heap access in the program.</p><p id="30a8">The stack can grow whenever extra memory is necessary, however the program is still limited by how much RAM is available</p><h1 id="c7a3">Resources</h1><div id="d29d" class="link-block"> <a href="https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap"> <div> <div> <h2>What and where are the stack and heap?</h2> <div><h3>A stack is used for static memory allocation and a heap for dynamic memory allocation, both stored in the computer's…</h3></div> <div><p>stackoverflow.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*JFgUrGZwu9L6W4mH)"></div> </div> </div> </a> </div><div id="2c9e" class="link-block"> <a href="https://pythontutor.com/visualize.html#mode=edit"> <div> <div> <h2>Python Tutor code visualizer: Visualize code in Python, JavaScript, C, C++, and Java</h2> <div><h3>Python Tutor: Visualize code in Python, JavaScript, C, C++, and Java</h3></div> <div><p>pythontutor.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/)"></div> </div> </div> </a> </div><div id="3804" class="link-block"> <a href="https://stackoverflow.com/questions/756861/whats-the-relationship-between-a-heap-and-the-heap"> <div> <div> <h2>What's the relationship between "a" heap and "the" heap?</h2> <div><h3>Nothing much, to be honest. I would imagine that the word heap was simply taken with it's everday (non-technical) usage…</h3></div> <div><p>stackoverflow.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*tiQisuHXoqfKnZ7C)"></div> </div> </div> </a> </div><p id="0ee7"><a href="https://www.programmerinterview.com/data-structures/difference-between-stack-and-heap/">https://www.programmerinterview.com/data-structures/difference-between-stack-and-heap/</a></p></article></body>

How applications work with the PC’s memory (Stack vs Heap)

Photo by Adi Goldstein on Unsplash

There are a lot of factors that affect how an application’s memory usage is managed, such as the OS and the language runtime (e.g. C++, Java, etc). But the focus of this article is to give a high level view of how memory is managed via the heap and the stack; which should remain consistent regardless of the factors mentioned above.

The first thing to know when talking about allocating memory on the stack or the heap is both of them are stored in RAM. Secondly the stack and heap is not to be confused with the stack and heap data structures. The stack and a stack data structure do share the LIFO property but there’s no commonality between the heap and a heap data structure.

What is the stack

Every thread has their own stack. The OS allocates the stack for every thread and when the thread exits, the stack is reclaimed. Each function call will have it’s own stack and it will be local to the function execution and the stack is reclaimed when the execution returns from the function.

To illustrate the functional scope using the stack see below code, and the following tool to visualize the stack allocation of the code step by step.

void func3() {
  int e = 4;
  int f = 5;
}

void func2() {
  int c = 2;
  int d = 3;
}

void func1() {
  int a = 0;
  int b = 1;
  
  func2();
}

int main() {
  func1();
  func3();
  return 0;
}
Figure 1: At line 8, when executing func2() from func1(), notice the stack allocation of both func1() and func2() is alive due to nested function calls.
Figure 2: At line 15, exiting func2() reclaims the stack (i.e. int c & d has be reclaimed)
Figure 3: And similarly when func1() exits, the stack with int a & b has be reclaimed.

The stack is much faster than the heap. This is due the localization and optimization in modern CPUs. This is because the data on the stack is contiguous and when the CPU fetches the data of a specific address, it also pulls in the neighboring address into the CPU’s cache because it’s very likely that the program will need the neighboring data as well.

Finally the stack is a fixed size that is determined by the OS at runtime when the thread is created. When the stack runs out of memory, it will result in a stack overflow exception, this is usually caused by calling nested functions too many times.

What is the heap

The head is global and is shared by all threads. This means there must be some sort of synchronization if multiple threads are accessing the same data. Also, allocation and deallocation doesn’t follow any fixed pattern and can occur ad-hocly. (Note: This applies mainly for languages like c++ where developers can control allocating and deallocating memory freely. But even with languages like JAVA, the same concept applies to the garbage collector. When you exit from a function, it’s not guaranteed the garbage collector will run and consequently the memory allocated in the heap from the function call is not freed on function exit. Eventual the garbage collector will run and reclaim the memory but it’s determined by the language runtime)

To help visualize heap allocation, see the below c++ code that explicitly allocated and deallocates memory on the heap to illustrate the global nature of the heap. It also illustrates how memory leaks can occur when working with languages that allows manual heap allocation.

void func3() {
  int e = 4;
  int f = 5;
}

void func2() {
  int* c = new int(2);
  int* d = new int(3);
  
  delete c;
}

void func1(int** a) {
  *a = new int(0);
  int* b = new int(1);
  
  func2();
  
  delete b;
}

int main() {
  int* a;
  func1(&a);
  func3();
  return 0;
}
Figure 4: At line 8 all integers up to func2() execution has been allocated on the heap. Notice before exiting from func2() allocation needs to be cleaned up (delete c)
Figure 5: Manually deleting allocation on the heap before exiting from func2(). Notice not deleting d will result in memory leak
Figure 6: Even after returning from func1() and still have access to int a because the scope of the heap is global

Note: There are many memory leaks in the above code that is not conveyed in the visualization. Any allocation on the heap must be cleaned up, either manually (e.g. via delete) or automated (via smart pointers).

The heap is much slower than the stack because there is much more complex bookkeeping involved in allocating and deallocating memory (especially in multithreaded environments). Since the heap is a global resource there is a performance hit in each allocation and deallocation because of requiring synchronization with “all” heap access in the program.

The stack can grow whenever extra memory is necessary, however the program is still limited by how much RAM is available

Resources

https://www.programmerinterview.com/data-structures/difference-between-stack-and-heap/

Stack
Heap
Memory Leak
C Plus Plus Language
Computer Science
Recommended from ReadMedium