L08 Dynamic Memory Allocation Inside Objects

#ece244

recap of dynamic memory allocation

Continuing from L07:

Recall! Again. Stack vs Heap

Stack stores the local variables and objects of a function
Heap stores the dynamically allocated memory

// example from the textbook
#include <iostream>
using namespace std;

int main(void) {
	int x = 10; // defining integer x = 10, stored on stack
	int* p = NULL; // defining pointer p initialized to NULL on stack
	p = &x; // make p point to address of x, still on stack
	*p = 5; // modify value of x through ptr p, by dereferencing p
	
	p = new int;
	// reassign ptr p to point to new dynamically allocated memory (heap)
	
	*p = 20; // assign value 20 to memory that p points to
	
	cout << "Value at p: " << *p << endl; // prints value stored at ptr p (20)
	cout << "Value of x: " << x << endl; // prints value of x (5)
	
	delete p; // frees the memory in the heap that p pointed to
	// p now points to garbage memory
	p = NULL; // pointing p to NULL
	return 0; 
}

dynamic memory allocation for arrays

int *arr = new int [10];
// dynamically allocate 10 integers
// arr returns address of first integer

arr[0] = 10;
arr[1] = 30;
arr[9] = 70;

delete arr; // this is not enough
delete []arr; // tells c++ that we're deleting an array from memory, valid

when are destructors called?

class Student {
	public:
		Student(); // constructor
		~Student(); // destructor
};
Student::Student() { cout << "Constructor"; }
Student::~Student() { cout << "Desctructor"; }

int main(void) {
	Student x;
	Student *z = new Student; // creates an object Student in heap
	delete z; // destructor is called, THEN the object gets freed from heap
	// destructor does NOT free from memory, it just gets called before it happens
	z = nullptr; // good practice
	return 0;
}
Tl;dr of this lecture: make sure to deallocate the dynamically-allocated memory within the class when the destructor is called.

Otherwise you'll have memory leak

file-20250928233526401.png