FirstHack Learn
Log in Sign up free
Lessons in this course 0/6 All courses Pointers and Memory in C

First year

Progress0 / 6 lessons
  1. 1. What an address really is
  2. 2. Declaring and dereferencing pointers
  3. 3. Pointers and arrays are not the same thing
  4. 4. Passing by pointer to change a caller variable
  5. 5. malloc, free and what a memory leak costs
  6. 6. Dangling pointers, double free and real crashes

Courses › Pointers and Memory in C

malloc, free and what a memory leak costs

The heap, allocating memory at runtime, and the arithmetic of a leak in a long-running program.

12 min read · Lesson 5 of 6 · Pro

Stack and heap

Your program's memory has two regions you control.

The stack holds local variables. It is automatic: a frame appears when a function is called and disappears when it returns. It is fast, and it is small — typically 8 MB on Linux, 1 MB on Windows. You cannot decide its lifetime.

The heap is a large pool you request from explicitly. You ask for bytes, you get an address, and those bytes stay yours until you hand them back. Slower to allocate, but you choose the size at runtime and you choose the lifetime.

Use the heap when: you do not know the size until the program runs, the data must outlive the function that created it, or the data is too big for the stack.

The rest of this lesson is Pro

The free lessons of Pointers and Memory in C finish what they start — read those first if you have not. This one goes further, and it is part of the paid half.

A pass opens the paid lessons of every course, the mock test papers and the company-wise series. It ends on its own date; nothing renews by itself.

Get a pass — from ₹29 for 7 days

Already bought one? Log in.