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

buffer-overflow, c

Solution

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.

Problem

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

Original source