Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain this code that runs a function without calling it explicitly?

The output of the code below is "Overflow", but I didn't explicitly call the func function. How does it work?

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

int copy(char *input)
{
    char var[20];
    strcpy(var, input);
    return 0;
}

int func(void)
{
    printf("Overflow\n");
    return 0;
}

int main(int argc, char *argv[])
{
    char str[] = "AAAABBBBCCCCDDDDEEEEFFFFGGGG";
    int *p = (int *)&str[24];
    *p = (int)func;

    copy(str);
    return 0;
}
like image 333
wilbeibi Avatar asked Nov 13 '12 13:11

wilbeibi


1 Answers

The copy function overflows the var buffer in the copy function and overwrites the main return address with the address of the func function.

When copy function returns, instead of returning to main after the copy function call, it returns to func function.

like image 179
ouah Avatar answered Nov 13 '22 04:11

ouah