Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack Smashing attempt giving segfault

I am trying to do an example from the Smashing the Stack for Fun and Profit in C, but am kind of stuck at a point, following is the code (I have a 64-bit machine with Ubuntu 64-bit):

int main()
{
    int x;

    x = 0;
    func(1,2,3);
    x = 1;
    printf("x is : %d\n", x);
}

void func(int a, int b, int c)
{
    char buffer[1];
    int *ret;

    ret = buffer + 17;
    (*ret) += 7;
}

The above code works fine and on returning the x=1 line is not executed, but I can't understand the logic behind ret = buffer + 17;, shouldn't it be ret = buffer + 16; i.e, 8bytes for buffer and 8 for the saved base pointer on stack.

Secondly, my understanding is that char buffer[1] is taking 8 bytes (owing to 64-bit arch) and if I increase this buffer to say buffer[2], still the same code should work fine, BUT this is not happening and it starts giving seg fault.

Regards, Numan

like image 613
user60103 Avatar asked Sep 10 '25 20:09

user60103


1 Answers

'char' on every architecture I've used is 8 bits wide irrespective of whether it's an 8 bit micro, a 16 bit micro, a 32 bit PC, or a 64 bit new PC. Int, on the other hand, tends to be the word size.

The order which the locals are put on the stack can be implementation specific. My guess is that your compiler is putting "int *ret" on the stack before "char buffer1". So, to get to the return address, we have to go through "char buffer1" (1 byte), "int *ret" (8 bytes), and the saved base pointer (8 bytes) for a total of 17 bytes.

Here's a description of the stack frame on x86 64-bit: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-035-computer-language-engineering-spring-2010/projects/x86-64

like image 79
Paul Avatar answered Sep 12 '25 15:09

Paul