Heap overflow and Stack overflow in C



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.

Heap overflow occurs when −

A) If we allocate dynamic large number of variables −

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

B) 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

Stack is a Last in First out data structure. It is used to store local variables which is used inside the function. Parameters are passed through this function and their return addresses.

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

Stack overflow occurs when −

C) 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 −

void calculate(int a) {    if (a== 0)       return;       a = 6;       calculate(a); } int main() {    int a = 5;    calculate(a); }

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

int main() {    A[20000][20000] }
Updated on: 2019-07-30T22:30:25+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements