Skip to content

Commit 3286b29

Browse files
committed
Add C++ memory structure section
1 parent cb95f0c commit 3286b29

8 files changed

+179
-10
lines changed

C++/04 C++ - Pointers.md C++/04 C++ - Pointers and Memory.md

+176-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Advanced C++ Crash Course (Pointers)
1+
# Advanced C++ Crash Course (Pointers and Memory)
22

33
Author: methylDragon
44
Contains an advanced syntax reference for C++
@@ -28,8 +28,10 @@ I'll be adapting it from the ever amazing Derek Banas: https://www.youtube.com/w
2828
2.5 [Arrays with Pointers](#2.5)
2929
2.6 [Indirection (Pointers of Pointers)](#2.6)
3030
2.7 [When to use Pointers and when to use References](#2.7)
31-
2.8 [Memory Management](#2.8)
32-
2.9 [Smart Pointers](#2.9)
31+
2.8 [Memory in C++](#2.8)
32+
2.8 [Heap and Stack](#2.9)
33+
2.10 [Memory Management](#2.10)
34+
2.11 [Smart Pointers](#2.11)
3335

3436

3537

@@ -194,6 +196,10 @@ i = 6
194196

195197
#### **Concepts**
196198

199+
![Image result for c++ memory](assets/pointers-in-c.jpg)
200+
201+
[Image Source](<https://simplesnippets.tech/cpp-pointers-concept-with-example/>)
202+
197203
Pointers are **variables** in and of themselves, that **STORE MEMORY ADDRESSES**. In effect, they act as signposts that POINT to memory addresses!
198204

199205
> A pointer `x` that points to variable `y` will have its own memory address, but will store the memory address that y is the alias for.
@@ -423,7 +429,170 @@ Pointers can also be altered to point to other memory addresses! But references
423429

424430

425431

426-
### 2.8 Memory Management <a name="2.8"></a>
432+
### 2.8 Memory in C++ <a name="2.8"></a>
433+
434+
[go to top](#top)
435+
436+
#### **Introduction**
437+
438+
Before we move on we should talk about how memory is stored in C++.
439+
440+
There are several main sections of memory used in any C++ program. They are ordered as follows. (Generally speaking. It's usually platform dependent.)
441+
442+
![img](assets/memoryLayoutC.jpg)
443+
444+
[Image Source](<https://www.geeksforgeeks.org/memory-layout-of-c-program/>)
445+
446+
Or in terms of the read-write capabilities of each block of memory,
447+
448+
![Image result for c++ memory](assets/main-qimg-0b429780923c55f6a803405694c5b7af.webp)
449+
450+
[Image Source](<https://www.quora.com/Is-it-a-design-fault-that-C++-itself-has-no-garbage-collection>)
451+
452+
We'll start from the bottom, following the first image.
453+
454+
If you're trying to interpret the second image in terms of the first, just take it that literals and static data are stored in the `unitialised` and `initialised data` segments, depending on whether they are initialised or not. `int i;` vs `int i = 5;`
455+
456+
#### **Text Segment**
457+
458+
The text segment is where the actual executable code instructions are stored. It's placed below the heap and stack to prevent any overflows from either from overwriting it.
459+
460+
Pretty smart.
461+
462+
#### **Initialised Data/Data Segment**
463+
464+
This is where all the data that is initialised with non-zero data at compile time is stored.
465+
466+
- The **read-only** section of this segment will go to **literals**, like strings. Eg: `char s[] = "rawr"`
467+
- The **read-write** section of this segment will go to static or global variables. Eg: `global int wow = 1;`
468+
469+
#### **Uninitialised Data/bss Segment**
470+
471+
(bss stands for "block started by symbol".)
472+
473+
All data here is initialised with 0. And it contains **all static or global data that is either explicitly initialised to 0 or does not have explicit initialisation in the source code.**
474+
475+
Some examples of stuff that's stored in the bss segment:
476+
477+
```c++
478+
static int a;
479+
global int b;
480+
481+
// This one will NOT be in the bss! Since it's local to main, and will actually go to the stack.
482+
int main(){
483+
int c = 0;
484+
return 0;
485+
}
486+
```
487+
488+
#### **Stack and Heap**
489+
490+
The stack and heap actually share the same segment, and typically grow in opposite directions from opposite ends of the segment. Though some optimisations and compilers might break this guideline.
491+
492+
![Image result for stack](assets/stack-1562909159143.jpg)
493+
494+
[Image Source](<http://bluegalaxy.info/codewalk/2018/08/12/python-how-to-implement-a-lifo-stack/>)
495+
496+
The stack follows last-in, first-out (LIFO) structure.
497+
498+
The top of the stack and heap are tracked using pointers. Once the two pointers meet, you've run out of memory. If you don't catch this, you'll get overflows, which will mean you're going to have a **bad time.**
499+
500+
Each time you call a function, a stack frame containing function variables, and information relating to the function caller's environments, return address, some machine registers, and other function-call related info are pushed to the stack. If you have a recursive function each recursive call actually generates a new stack frame on the stack.
501+
502+
> - The stack grows and shrinks as functions push and pop local variables
503+
> - There is no need to manage the memory yourself, variables are allocated and freed automatically
504+
> - The stack has size limits
505+
> - Stack variables only exist while the function that created them, is running
506+
> - This includes the main() function!!
507+
>
508+
> <https://www.gribblelab.org/CBootCamp/7_Memory_Stack_vs_Heap.html>
509+
510+
#### **Heap**
511+
512+
The heap is where dynamic memory allocation typically happens.
513+
514+
You manage it by using `malloc`, `realloc`, `free` (C functions), or the newer `new`, `new[]`, `delete`, and `delete[]` C++ operators, which are better and almost always better to use.
515+
516+
Every thread, library, or module in a single program process has access to this data segment, since they're essentially global.
517+
518+
It's **normally slower to access heap data than stack data since you need to use pointers to access them.**
519+
520+
521+
522+
### 2.9 Heap and Stack <a name="2.9"></a>
523+
524+
[go to top](#top)
525+
526+
There's actually more to go through for the heap and stack, since they're the two data segments that you'll encounter most often.
527+
528+
> ## Stack vs Heap Pros and Cons
529+
>
530+
> ### Stack
531+
>
532+
> - Very fast access
533+
> - Don't have to explicitly de-allocate variables
534+
> - Space is managed efficiently by CPU, memory will not become fragmented
535+
> - Local variables only
536+
> - Limit on stack size (OS-dependent)
537+
> - Variables cannot be resized
538+
>
539+
> ### Heap
540+
>
541+
> - Variables can be accessed globally
542+
> - No limit on memory size
543+
> - (Relatively) slower access
544+
> - No guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed
545+
> - You must manage memory (you're in charge of allocating and freeing variables)
546+
> - Variables can be resized using `realloc()`
547+
>
548+
> ## When to use the Heap?
549+
>
550+
> When should you use the heap, and when should you use the stack?
551+
>
552+
> If you need to allocate a **large block of memory** (e.g. a large array, or a big struct), and you need to **keep that variable around a long time** (like a global), then you should **allocate it on the heap**.
553+
>
554+
> If you are dealing with **relatively small variables that only need to persist as long as the function using them is alive**, then you should **use the stack**, it's easier and faster.
555+
>
556+
> If you need variables like arrays and structs that can **change size dynamically** (e.g. arrays that can grow or shrink as needed) then you will likely need to **allocate them on the heap**, and use dynamic memory allocation functions like `malloc()`, `calloc()`, `realloc()` and `free()` to manage that memory "by hand".
557+
>
558+
> <https://www.gribblelab.org/CBootCamp/7_Memory_Stack_vs_Heap.html>
559+
560+
#### **Allocating to Stack**
561+
562+
It's fairly simple to allocate stuff to the stack. Just make sure that they're specifically **local variables** in a function (which can be main()!)
563+
564+
These variables are **automatically allocated**.
565+
566+
```c++
567+
int main(){
568+
int c = 0;
569+
return 0;
570+
}
571+
572+
void foo(){
573+
int a = 1;
574+
}
575+
```
576+
577+
#### **Allocating to Heap**
578+
579+
You **can't declare variables on the heap.** You can only create variables anonymously, then point to them with a named **pointer**.
580+
581+
So, allocating to the heap is trickier. You need to **explicitly allocate** the memory as a pointer.
582+
583+
The variables pointed at by the pointer are on the heap, and are **dynamically allocated.**
584+
585+
```c++
586+
int* ptr = new int; // ptr is assigned 4 bytes in the heap
587+
int* array = new int[10]; // array is assigned 40 bytes in the heap
588+
589+
// Or later, when we go through smart pointers (which are better than raw pointers)
590+
std::unique_ptr<someType> uniqueptr(new int(1));
591+
```
592+
593+
594+
595+
### 2.10 Memory Management <a name="2.10"></a>
427596
428597
[go to top](#top)
429598
@@ -433,6 +602,8 @@ I have to say it here, since we've covered pointers. The reason why C++ is so po
433602
434603
So here's a small primer! For **dynamic (runtime) memory management.**
435604
605+
(We will not be going through the old `malloc`, `free`, `realloc` and related C functions, since the operators C++ provisions for are way better.)
606+
436607
437608
438609
#### **new and new[]**
@@ -528,9 +699,7 @@ str2 = std::move(str1);
528699

529700

530701

531-
532-
533-
### 2.9 Smart Pointers <a name="2.9"></a>
702+
### 2.11 Smart Pointers <a name="2.11"></a>
534703

535704
[go to top](#top)
536705

C++/06 C++ - Templates.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
Author: methylDragon
44
Contains an advanced syntax reference for C++
5-
This time, we'll be going through C++ templates!!
5+
This time, we'll be going through C++ templates and template metaprogramming!
66

77
------
88

Binary file not shown.

C++/assets/memoryLayoutC.jpg

39.7 KB
Loading

C++/assets/pointers-in-c.jpg

21.6 KB
Loading

C++/assets/stack-1562909159143.jpg

10.2 KB
Loading
49.4 KB
Loading

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,10 @@ Most of these can be read through in under an hour, and they're pitched at the b
4040
- [Introduction and Basic Syntax](./C++/01%20C++%20-%20Introduction.md)
4141
- [Functions and File IO](./C++/02%20C++%20-%20Functions%20and%20File%20IO.md)
4242
- [Object-Oriented Syntax](./C++/03%20C++%20-%20Object-Oriented%20Syntax.md)
43-
- [Pointers](./C++/04%20C++%20-%20Pointers.md)
43+
- [Pointers and Memory](./C++/04%20C++%20-%20Pointers%20and%20Memory.md)
4444
- [Data Structures (Containers)](./C++/05%20C++%20-%20Data%20Structures%20(Containers).md)
4545
- [Templates](./C++/06%20C++%20-%20Templates.md)
46-
- [Threading](./C++/07%20C++%20-%20Threading.md)
46+
- [Threading](./C++/07%20C++%20-%20Concurrency.md)
4747
- [Tips and Tricks](./C++/08%20C++%20-%20Tips%20and%20Tricks.md)
4848
- [(Bonus) Headers](./C++/Bonus%20Notes/BONUS%20C++%20-%20Headers.md)
4949

0 commit comments

Comments
 (0)