Reputation:
In C or C++, can one obtain the size occupied by a function, allocate memory dynamically with malloc()
for it, make a copy, and execute it with a function pointer cast?
Am just curious about it, and here is a non-working example:
#include <stdio.h>
int main(void)
{
void *printf_copy = malloc(sizeof(printf));
((int(*)(const char *, ...))printf_copy)("%s\n", "hello, world");
return 0;
}
Upvotes: 0
Views: 105
Reputation: 368
Unless the code is self-modifying, (and if it is, you've been a very bad developer), there is no point in copying a function, even if you could safely do so - the copied would always look exactly the same as teh original, so why do it? There are lots of reasons to avoid trying, as explained by others.
If you want to execute a function via a pointer, just call it where it is. If you want it to have its own execution, thread it off.
Upvotes: 0
Reputation: 36401
First, you can't get size of the code used by a function such a way, there is no C operator or function for this. The only way is to get it from ELF headers, etc. Beware that a function may call others, so you usually need some kind of linking... and that function code may not be relative!
Second, the only way to get some executable memory is through mmap
, malloc
only gives you heap memory which is usually not executable part of the process space.
Upvotes: 1