title: Copy a function in memory and execute it
body: <p>I would like to know how in C in can copy the content of a function into memory and the execute it?</p>
  
  <p>I'm trying to do something like this:</p>
  
  <pre><code>typedef void(*FUN)(int *);
  char * myNewFunc;
  
  char *allocExecutablePages (int pages)
  {
      template = (char *) valloc (getpagesize () * pages);
      if (mprotect (template, getpagesize (), 
            PROT_READ|PROT_EXEC|PROT_WRITE) == -1) {
          perror ("mprotect");
      } 
  }
  
  void f1 (int *v) {
      *v = 10;
  }
  
  // allocate enough spcae but how much ??
  myNewFunc = allocExecutablePages(...)
  
  /* Copy f1 somewere else
   * (how? assume that i know the size of f1 having done a (nm -S foo.o))
   */
  
  ((FUN)template)(&amp;val);
  printf("%i",val);
  </code></pre>
  
  <p>Thanks for your answers</p>