title: Getting function location in executable
body: <p>I need the location of a code section in the executable (begin and ebn address). I tried to use two dummy functions:</p>
  
  <pre><code>void begin_address(){}
  void f(){
      ...
  }
  void end_address(){}
  
  ...
  
  printf("Function length: %td\n", (intptr_t)end_address - (intptr_t)begin_address);
  </code></pre>
  
  <p>The problem is, that using <code>-O4</code> optimization with <code>gcc</code> I got a negative length. It seems that this does not work with optimizations.</p>
  
  <p>I compiled <code>f</code> to assembly, and tried the following:</p>
  
  <pre><code>__asm__(
  "func_begin:"
  "movq $10, %rax;"
  "movq $20, %rbx;"
  "addq %rbx, %rax;"
  "func_end:"
  );
  
  extern unsigned char* func_begin;
  extern unsigned char* func_end;
  
  int main(){
      printf("Function begin and end address: %p\t%p\n", func_begin, func_end);
      printf("Function length: %td\n", (intptr_t)func_end - (intptr_t)func_begin);
  }
  </code></pre>
  
  <p>The problem is that even without optimization I am getting some strange output:</p>
  
  <pre><code>Function begin and end address: 0x480000000ac0c748  0xf5158b48e5894855
  Function length: -5974716185612615411
  </code></pre>
  
  <p>How can I get the location of a function in the executable? My second question is whether referring to this address as <code>const char*</code> is safe or not. I am interested in both 32 and 64 bit solutions if there is a difference.</p>