We are dealing with C here. I'm just had this idea, wondering if it is possible to access the point in memory where a function is stored, say foo
and copying the contents of the function to another point in memory. Specifically, I'm 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 running it gives a bus error: Bus error: 10
. I'm trying to copy over the contents of function foo
into a space of memory bar
and then executing the newly created function bar
.
This is for no other reason than to see if such a thing is possible, to reveal the intricacies of the C language. I'm not thinking about what practical uses this has.
I'm looking for guidance getting this to work, or otherwise to be told, with a reason, why this won't work
EDIT Looking at some of the answers and learning about read, write, and executable memory, it just dawned upon me that it would be possible to create functions on the fly in C by writing to executable memory.
sizeof *foo
seems even remotely valid? – Subscriptsizeof foo
isn't just going to return the size of the pointer (i.e. 4 or 8)? – Basebornvoid*
is perfectly well-defined. – Finddladdr
), requires such casts to work. It's unlikely that the C committee intended to make such a basic function undefined behaviour. – Findmemcpy(&bar, &foo
is copying foo to the pointer bar, not to the memory block pointed to by bar. – Requiescat