Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting The Size of a C++ Function

Tags:

I was reading this question because I'm trying to find the size of a function in a C++ program, It is hinted at that there may be a way that is platform specific. My targeted platform is windows

The method I currently have in my head is the following:
1. Obtain a pointer to the function
2. Increment the Pointer (& counter) until I reach the machine code value for ret
3. The counter will be the size of the function?

Edit1: To clarify what I mean by 'size' I mean the number of bytes (machine code) that make up the function.
Edit2: There have been a few comments asking why or what do I plan to do with this. The honest answer is I have no intention, and I can't really see the benefits of knowing a functions length pre-compile time. (although I'm sure there are some)

This seems like a valid method to me, will this work?

like image 620
Adam Avatar asked Apr 13 '11 21:04

Adam


People also ask

What is the size of a function in C?

The sizeof() function in C is a built-in function that is used to calculate the size (in bytes)that a data type occupies in ​the computer's memory.

How do I get the size of a type in C++?

The size of a variable depends on its type, and C++ has a very convenient operator called sizeof that tells you the size in bytes of a variable or a type. The usage of sizeof is simple. To determine the size of an integer, you invoke sizeof with parameter int (the type) as demonstrated by Listing 3.5.

What is sizeof int in C?

So, the sizeof(int) simply implies the value of size of an integer. Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.


1 Answers

Wow, I use function size counting all the time and it has lots and lots of uses. Is it reliable? No way. Is it standard c++? No way. But that's why you need to check it in the disassembler to make sure it worked, every time that you release a new version. Compiler flags can mess up the ordering.

static void funcIwantToCount() {    // do stuff } static void funcToDelimitMyOtherFunc() {    __asm _emit 0xCC    __asm _emit 0xCC    __asm _emit 0xCC    __asm _emit 0xCC }  int getlength( void *funcaddress ) {    int length = 0;    for(length = 0; *((UINT32 *)(&((unsigned char *)funcaddress)[length])) != 0xCCCCCCCC; ++length);    return length; } 

It seems to work better with static functions. Global optimizations can kill it.

P.S. I hate people, asking why you want to do this and it's impossible, etc. Stop asking these questions, please. Makes you sound stupid. Programmers are often asked to do non-standard things, because new products almost always push the limits of what's availble. If they don't, your product is probably a rehash of what's already been done. Boring!!!

like image 50
Jordan Avatar answered Sep 17 '22 12:09

Jordan