Dynamic Memory Allocation + Pointers

Pointers

  • Pointer — stores the address of a variable
  • int *a = &ba is a pointer to the address of b → use *a to access b
  • int &a = ba is alias (reference) to b → both share the same address → use a to access b
arr[3] = { 5, 10, 20 }; // *arr → 5 // *(arr + 1) → 10 // For 2-D array: *(*arr + 1) → arr[0][1] *(*(arr + 1)) → arr[1][0]

Dereferencing

  • Retrieve the data stored at the memory location a pointer points to.
  • Void pointers give great flexibility — they can point to any data type.
    But to dereference → first cast it to a concrete data type.

Memory Leak

When a program forgets to deallocate memory, making it unavailable for future use.

m = malloc(5); m = NULL; // Allocates 5 bytes on heap → stores address in pointer m // Sets m = NULL → program loses that address // No pointer refers to that memory anymore // → Cannot be accessed or freed for the lifetime of the program

Dangling Pointer

  • delete ptr → only frees the memory, but pointer variable still exists pointing to the freed location → undefined behaviour
if(ptr != NULL) // Guard: deleting NULL pointer → Undefined Behavior { delete ptr; ptr = NULL; // Set to NULL after deletion → avoids dangling pointer }

Wild Pointer

Uninitialized pointers — they point to a random memory location, causing unpredictable behaviour.

int* p; // No initialization → points to unknown memory location *p = 12; // ❌ BAD — modifying an unknown memory location // ───────────────────────────────────────────────── int a = 10; int* p = &a; // ✅ Not a wild pointer — points to a known value *p = 12; // ✅ OK — value of a gets changed // ───────────────────────────────────────────────── int* p = (int*)malloc(sizeof(int)); *p = 12; // ✅ Also acceptable

const Pointers

  • const int* ptr — pointer to a const int → can modify ptr itself, but cannot modify the value it points to
  • int* const ptrconst pointer to an intcannot modify ptr itself, but can modify the value it points to
// const int* ptr const int a = 10; const int* ptr = &a; *ptr = 5; // ❌ wrong ptr++; // ✅ right
// int* const ptr int a = 10; int* const ptr = &a; *ptr = 5; // ✅ right ptr++; // ❌ wrong

Smart Pointers

When we forget to deallocate memory → may get a memory leak that can crash the program.
Java & C# have Garbage Collection to smartly reclaim unused memory.
In C++, use Smart Pointers — whenever the object goes out of scope, memory is freed automatically → no need for delete.

Smart pointers are classes that wrap a raw pointer to manage memory efficiently.
  • unique_ptr — single ownership model → only one unique_ptr per object → to reassign, first release the current object.
  • shared_ptr — multiple pointers can share one object → maintains a Reference Counter → when count reaches 0, memory is freed.
  • weak_ptr — similar to shared_ptr but does not increase the reference count → avoids circular dependency.

malloc, calloc, realloc

  • malloc (memory allocation) — dynamically allocates memory of a specified size → returns void* castable to any type → initialized with garbage values.
  • calloc (contiguous allocation) — same as malloc but initializes each block to 0.
  • realloc (re-allocation) — resizes previously allocated memory → existing values preserved, new blocks contain garbage values.
int* p = (int*) malloc (n * sizeof(int)); // memory = 4*n bytes (1 int = 4 bytes) int* p = (int*) calloc (n, sizeof(int)); p = (int*) realloc(p, n * sizeof(int)); if(p == NULL) "Memory not allocated" free(p); // frees memory

Memory Layout of a C Program

  • When the program starts → code gets copied to main memory (RAM).
  • Stack — holds contiguous memory occupied by functions (limited / local scope).
    • Very fast → only 1 CPU instruction because only the stack pointer moves.
    • Memory automatically freed once a variable goes out of scope.
  • Heap — stores data via dynamic memory using pointers (universal scope).
    • Slower — must maintain a record of all free memory blocks (free list).
    • Must be freed explicitly using delete / free.
    • Benefit: main → f1 → f2 → f3 (all on stack) — but if f1 allocates on heap, it doesn't have to wait for f2 & f3 to finish; f1 itself creates and deletes its memory independently.
  • Initialized & Uninitialized data segments — hold global variables (initialized and uninitialized respectively).
int* create() { int* arr = new int[50]; // assigned using heap // int arr[50]; → CANNOT be accessed in main (stack — local scope) return arr; } int main() { int* brr = create(); // stores the returned pointer brr[3] = 5; // access arr from create() via pointer delete[] brr; // remember to free heap memory! }
NOTE — The name arr is local inside create(), but the memory is on the heap (global scope) → accessible globally if the pointer is appropriately shared.

new keyword

  • new → internally calls malloc to allocate memory and calls the constructor.
  • int arr; → creates a block of int on the stack and names it arr.
  • int* ptr = new int; → creates a block of int on the heap and assigns its address to ptr.
  • int* ptr = new int  and  int* ptr = new int()  → Both are valid.
  • Can allocate any data type or custom class: node* head = new node;
    • With initial value → float* a = new float(45.67);
    • As array → int* a = new int[7];
  • delete must be used — memory is on heap → else memory leak!
    • For object → delete name;    For array → delete[] name;

malloc / free  vs  new / delete

NOTE: Points below mention malloc but apply similarly to calloc & realloc.
Feature malloc / free new / delete
Language C library function (usable in C++ too) C++ specific operator
Memory allocation Allocates memory on heap Allocates memory on heap
Constructor / Destructor Does NOT call constructor or destructor Calls constructor (new) and destructor (delete)
Return type Returns void* — must be cast Returns correctly typed pointer
⚠️ Never mix them:
• Do NOT use free with new → destructor won't be called → resources not cleaned up.
• Do NOT use delete with mallocundefined behavior (may crash, give random errors, or seem to work normally).

Always follow convention — never experiment with heap. DANGER !!

Comments

Popular posts from this blog

Templates (for CP)

DSA Trees + Heap