Using this answer (and this follow-up) as inspiration I was looking at ways to do some functional programming in C (for which there are already plenty of interesting discussions on this site). What I'd like to know is how and when it's possible to use the approach taken in the linked code, of casting a string to a function pointer and executing it. For example on my machine (OSX 10.10, Darwin 14.0.0, GCC 4.8.3) I can compile and run
int eax = ((int(*)())("\xc3 <- This returns the value of the EAX register"))();
(always returning 0, which is what I'd expect if the program does nothing else) but
#include <stdio.h>
int main() {
const char* lol = "\x8b\x5c\x24\x4\x3d\xe8\x3\x0\x0\x7e\x2\x31\xc0\x83\xf8\x64\x7d\x6\x40\x53\xff\xd3\x5b\xc3\xc3 <- Recursively calls the function at address lol.";
int i = ((int(*)())(lol))(lol);
printf("i: %d\n",i);
return 0;
}
segfaults. On the other hand codepad successfully runs the second example giving the correct answer i: 100
.
When is it possible to execute from strings? And is there a way to make it (relatively) consistent?
(I can reasonably guess this is undefined behaviour and I know I'm going to increase worldwide unemployment by using it.)