We are dealing with C here. I just had this idea, I wonder if it is possible to access the memory point where the function is stored, say foo and copy the contents of the function to another memory point. In particular, I am trying to get the following to work:
#include <stdlib.h> #include <stdio.h> #include <string.h> void foo(){ printf("Hello World"); } int main(){ void (*bar)(void) = malloc(sizeof foo); memcpy(&bar, &foo, sizeof foo); bar(); return 0; }
But at startup, it gives a bus error: Bus error: 10 . I am trying to copy the contents of the function foo to the memory space of bar , and then execute the newly created function bar .
This is not for any other reason than to see if it is possible to reveal the subtleties of the C language. I do not think about the practical application of this.
I am looking for guidance to make this work, or, otherwise, to be said, with a reason why this will not work
EDIT Looking at some answers and learning about reading, writing, and executable memory, it just became clear to me that it would be possible to create functions on the fly in C by writing to executable memory.
c memory function-pointers memcpy
theideasmith
source share