Find size of a function in C

The space for code is statically allocated by the linker when you build the code. In the case where your code is loaded by an operating system, the OS loader requests that memory from the OS and the code is loaded into it. Similarly static data as its name suggests is allocated at this time, as is an initial stack (though further stacks may be created if additional threads are created).

With respect to determining the size of a function, this information is known to the linker, and in most tool-chains the linker can create a map file that includes the size and location of all static memory objects (i.e. those not instantiated at run-time on the stack or heap).

There is no guaranteed way of determining the size of a function at run-time (and little reason to do so) however if you assume that the linker located functions that are adjacent in the source code sequentially in memory, then the following may give an indication of the size of a function:

int first_function()
{
   ...
}

void second_function( int arg )
{
    ...
}

int main( void )
{
    int first_function_length = (int)second_function - (int)first_function ;
    int second_function_length = (int)main - (int)second_function ;

}

However YMMV; I tried this in VC++ and it only gave valid results in a "Release" build; the results for a "Debug" build made no real sense. I suggest that the exercise is for interest only and has no practical use.

Another way of observing the size of your code of course is to look at the disassembly of the code in your debugger for example.


They're (normally) separate from either the stack or heap.

There are ways to find their size, but none of them is even close to portable. If you think you need/want to know the size, chances are pretty good that you're doing something you probably ought to avoid.


Functions are part of text segment (which may or may not be 'heap') or its equivalent for the architecture you use. There's no data past compilation regarding their size, at most you can get their entry point from symbol table (which doesn't have to be available). So you can't calculate their size in practice on most C environments you'll encounter.

Tags:

C