Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overflowing stack with huge local variable?

Tags:

c

linux

As it is said that 8 mb of stack is given to each process. This stack will be used to store local variables. So if i take an array of size max than of the stack , it must overflow ??

 int main()
{
int arr[88388608];
int arr1[88388608];
int arr2[88388608];
while(1);
return 0;
}

But i am unable to get the result !

like image 550
sourav punoriyar Avatar asked Feb 19 '16 07:02

sourav punoriyar


1 Answers

Welcome to the world of optimizing compilers!

Because of the as-if rule, the compiler is only required to build something that would have same observable results as your original code. So the compiler if free to:

  • remove the unused arrays
  • remove the empty loop
  • store the dynamic arrays from main outside of the stack - because main is a special function that shall be called only once by the environment

If you want to observe the stack overflow (the bad one, not our nice site :-) ), you should:

  • use some code to fill the arrays
  • compile with all optimization removed and preferently in debug mode to tell the compiler do what I wrote as accurately as you can

The following code does SIGSEGV with CLang 3.4.1 when compiled as cc -g foo.c -o foo

#include <stdio.h>

#define SIZE 88388608

void fill(int *arr, size_t size, int val) {
    for (size_t i=0; i<size; i++) {
        arr[i] = val;
    }
}    
int main() {
    int arr[SIZE];
    int arr1[SIZE];
    int arr2[SIZE];

    fill(arr, SIZE, 0);
    fill(arr1, SIZE, 0);
    fill(arr2, SIZE, 0);
    printf("%d %d %d\n", arr[12], arr1[15], arr2[18]);

    return 0;
}

and even this code works fine when compiled as -O2 optimization level... Compilers are now too clever for me, and I'm not brave enough to thoroughly look at the assembly code which would be the only real way to understand what is actually executed!

like image 145
Serge Ballesta Avatar answered Oct 12 '22 05:10

Serge Ballesta