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.
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
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
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
No, it generally won't. (BTW
memcmp is just comparing bytes, not "moving" or "copying" them).
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
PS. You really should motivate your question, which looks like an XY problem.