Stacksmashing without even accessing any data

37 views Asked by At

On my machine, the following code apparently produces stacksmashing:

#include <stdio.h>
#include <stdlib.h>

void function2(int* data);
void function1();

void function2(int* data)
{
    printf("grps ");
    printf(" ");
    printf(" one more line\n");
}

void function1()
{
    printf("function1_checkpoint1\n");
    int *tempData[520721];
    function2(tempData);
}

int main()
{
    printf("main_checkpoint1\n");
    function1();
    printf("main_checkpoint2\n");
    return 0;
}

If it does not crash on your machine, try replacing 520721 by some more crazy number like 10 million. The output I have is:

main_checkpoint1

And then crash. If I replace 520721 by 520720 I get:

main_checkpoint1
function1_checkpoint1

And then also crash. If instead I replace printf(" ") by printf("") (suppress the space, printing an empty string), the program is running normally and I get

main_checkpoint1
function1_checkpoint1
grps  one more line
main_checkpoint2

Finally, replacing int *tempData[520721]; by int *tempData=malloc(520721*sizeof(int)); with subsequent testing of the success of malloc() and usage of free(tempData); have always worked in all the cases I tested.

As you can see, all I am doing is calling a first function in main, which creates a very big local int table, and then passing the pointer to this int table, to a second function. And the second function does nothing except printfs and doesn't even touch to the pointer or the data it points to.

I was just wondering what on earth was going on in my machine...why is this code producing a crash?

Thanks very much for your insight!

1

There are 1 answers

5
zneak On BEST ANSWER

It's crashing because you're causing a stack overflow. That huge array is allocated on the stack, and the stack isn't that big.

Simply allocating a variable is enough to make it move the stack pointer. You don't write to it, but when you then call your other function, your program tries to write to the stack, past the huge array, to allocate the next stack frame. This is when it crashes.

You've already got the solution: use a dynamic allocation instead.