Executing machine code in memory
c, casting, function-pointers, segmentation-fault
Solution
It seems to me you're loading an ELF image and then trying to jump straight into the ELF header? http://en.wikipedia.org/wiki/Executable_and_Linkable_Format
If you're trying to execute another binary, why don't you use the process creation functions for whichever platform you're using?
Problem
I'm trying to figure out how to execute machine code stored in memory. I have the following code: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { FILE* f = fopen(argv[1], "rb"); fseek(f, 0, SEEK_END); unsigned int len = ftell(f); fseek(f, 0, SEEK_SET); char* bin = (char*)malloc(len); fread(bin, 1, len, f); fclose(f); return ((int (*)(int, char *)) bin)(argc-1, argv[1]); } ``` The code above compiles fine in GCC, but when I try and execute the program from the command line like this: ``` ./my_prog /bin/echo hello ``` The program segfaults. I've figured out the problem is on the last line, as commenting it out stops the segfault. I don't think I'm doing it quite right, as I'm still getting my head around function pointers. Is the problem a faulty cast, or something else?