How'd I go about copying a function in memory to a different location and be able to run it from the new location in C++?

I thought maybe memcmp would work, but I'm not sure how I'd go about running it after it copied to the new location.

  • 2
    Why do you ask? What is the the usage scenario? Oct 25, 2016 at 18:51
  • 1
    BTW, the reverse-engineering tag is inappropriate. Oct 25, 2016 at 19:10
  • Without additional motivation (so you should edit your question to improve it) I am tempted to vote for close (or downvote) the question. Oct 25, 2016 at 19:26

1 Answer 1


You cannot do that (copying the code of some function) in a portable way. The machine code of some function cannot be moved without care, because in many instruction sets the code depends of its position. For example, many CALL or JUMP machine instructions are relative to the program counter (so if you "move" them they will jump to an erroneous location). Details are implementation specific and vary with the compiler, the calling conventions, the instruction set, the ABI, the operating system. Read more about linkers, e.g. Levine's Linkers & loaders book.

I thought maybe memcpy would work

No, it generally won't. (BTW memcmp is just comparing bytes, not "moving" or "copying" them).

Read about Position Independent Code and Relocation (& virtual address space)

Perhaps you should consider generating machine code, using some JIT compilation library like GNU lightning, or GNU libjit, or asmjit, or GCCJIT, or LLVM. On POSIX systems, you could simply emit some C or C++ code into some temporary file, compile it (into a position independent shared object), and use dlopen(3) & dlsym(3) (see here for more).

but I'm not sure how I'd go about running it after it copied to the new location

If the new location contains valid executable machine code (but see W^X), you just use some function pointer (and call it). But beware of undefined behavior.

PS. You really should motivate your question, which looks like an XY problem.

  • When you say "Beware of undefined behaviour", you mean, "The whole thing is undefined behaviour from start to finish and you're absolutely dependent on behaviour your implementation happens to define", right? You make it sound like if he slips up it'll be UB.
    – DeadMG
    Oct 25, 2016 at 19:19
  • I was more precisely thinking of calling (thru a function pointer) some "wrong" machine code (e.g. like some memcpy-ed one) Oct 25, 2016 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.