Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smashing a stack: Why is this code working?

I am following the "Smashing the Stack for fun and profits" http://insecure.org/stf/smashstack.html .

I wonder why my code is working though I wrote it to make a segmentation fault.

#include <stdio.h>
#include <string.h>

void function(char *str){
    char buffer[16];
    strcpy(buffer, str);
}

int main(void)
{
    char large_string[256];
    int i;

    for(i = 0; i < 255; i++)
        large_string[i];

    function(large_string);
    return 0;
}
like image 705
torr Avatar asked Mar 20 '26 19:03

torr


1 Answers

It's just because your large_string is not initialized properly: it contains garbage, and its length (number of bytes till '\0') is most probably much less than 256 (e.g. on my machine the fourth byte of large_string is zero so strcpy copies just 4 bytes).

Make it

for(i = 0; i < 254; i++)
    large_string[i] = 'A';
large_string[255] = '\0';

and you'll get segmentation fault.

like image 189
nullptr Avatar answered Mar 24 '26 05:03

nullptr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!