wilbeibi
wilbeibi

Reputation: 3454

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;
}

Upvotes: 8

Views: 228

Answers (1)

ouah
ouah

Reputation: 145829

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.

Upvotes: 10

Related Questions