title: How to determine the length of a function?
body: <p>Consider the following code that takes the function f(), copies the function itself in its entirety to a buffer, modifies its code and runs the altered function. In practice, the original function that returns number 22 is cloned and modified to return number 42.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  #define ENOUGH 1000
  #define MAGICNUMBER 22
  #define OTHERMAGICNUMBER 42
  
  int f(void)
  {
      return MAGICNUMBER;
  }
  
  int main(void)
  {
      int i,k;
      char buffer[ENOUGH];
      /* Pointer to original function f */
      int (*srcfptr)(void) = f;
      /* Pointer to hold the manipulated function */
      int (*dstfptr)(void) = (void*)buffer;
      char* byte;
      memcpy(dstfptr, srcfptr, ENOUGH);
      /* Replace magic number inside the function with another */
      for (i=0; i &lt; ENOUGH; i++) {
          byte = ((char*)dstfptr)+i;
          if (*byte == MAGICNUMBER) {
              *byte = OTHERMAGICNUMBER;
          }
      }
  
      k = dstfptr();
      /* Prints the other magic number */
      printf("Hello %d!\n", k);
      return 0;
  }
  </code></pre>
  
  <p>The code now relies on just guessing that the function will fit in the 1000 byte buffer. It also violates rules by copying too much to the buffer, since the function f() will be most likely a lot shorter than 1000 bytes.</p>
  
  <p>This brings us to the <strong><em>question</em></strong>: Is there a method to figure out the size of any given function in C? Some methods include looking into intermediate linker output, and guessing based on the instructions in the function, but that's just not quite enough. Is there any way to be sure?</p>
  
  <hr>
  
  <p>Please note: It compiles and works on my system but doesn't quite adhere to standards because conversions between function pointers and void* aren't exactly allowed:</p>
  
  <pre><code>$ gcc -Wall -ansi -pedantic fptr.c -o fptr
  fptr.c: In function 'main':
  fptr.c:21: warning: ISO C forbids initialization between function pointer and 'void *'
  fptr.c:23: warning: ISO C forbids passing argument 1 of 'memcpy' between function pointer and 'void *'
  /usr/include/string.h:44: note: expected 'void * __restrict__' but argument is of type 'int (*)(void)'
  fptr.c:23: warning: ISO C forbids passing argument 2 of 'memcpy' between function pointer and 'void *'
  /usr/include/string.h:44: note: expected 'const void * __restrict__' but argument is of type 'int (*)(void)'
  fptr.c:26: warning: ISO C forbids conversion of function pointer to object pointer type
  $ ./fptr
  Hello 42!
  $
  </code></pre>
  
  <p>Please note: on some systems executing from writable memory is not possible and this code will crash. It has been tested with gcc 4.4.4 on Linux running on x86_64 architecture.</p>