Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Heap overflow and Stack overflow



Heap and stack overflows are both types of buffer overflows that occur when a program attempts to write data beyond the allocated boundary of a buffer.

Heap Overflow

Heap is used to store dynamic variables. It is a region of process's memory. malloc(), calloc(), resize() all these inbuilt functions are generally used to store dynamic variables.

Following are the regions where heap overflow occurs ?

If we allocate dynamic large number of variables

int main() {
   float *ptr = (int *)malloc(sizeof(float)*1000000.0));
}

If we continuously allocate memory and do not free after using it.

int main() {
   for (int i=0; i<100000000000; i++) {
      int *p = (int *)malloc(sizeof(int));
   }
}

Stack Overflow

The stack is a memory region used for storing function call information, local variables and returns addresses. An stack overflow occurs when the program attempts to write data beyond the allocated size of a buffer on the stack.

If a program consumes more memory space, then stack overflow will occur as stack size is limited in computer memory.

Following are the regions where stack overflow occurs ?

If a function is called recursively by itself infinite times then stack will be unable to store large number of local variables, so stack overflow will occur.

#include<stdio.h>
void calculate(int a) {
   if (a== 0)
      return;
      a = 6;
      calculate(a);
}
int main() {
   int a = 5;
   calculate(a);
}

If we declare a large number of local variables or declare a large dimensional array or matrix can result in stack overflow.

int main() {
   A[20000][20000];
}

Heap vs Stack Overflow

Here, is the comparison between heap overflow and stack overflow:

Features Heap Overflow Stack Overflow
Memory Type Dynamic memory allocation. Local function memory allocation.
Cause Continuous allocation without freeing memory. Excessive recursion or large local variables.
Error Impact Memory leak, performance degradation. Program Crash
Access Speed Slower (non-contiguous memory). Faster (Contiguous memory).
Size Limit Large, limited by system memory. Smaller predefined by OS.
Deallocation Manual (requires free() or delete). Automatic (Freed when function exits).
Updated on: 2025-06-18T18:31:25+05:30

589 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements