Search code examples
c++cfunctionsizeofdynamic-memory-allocation

Is there a way to obtain size of function and allocate memory for it to be copied and executed?


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

Solution

  • 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.