Find size of a function in C

后端 未结 9 1732
别跟我提以往
别跟我提以往 2020-12-10 16:37

I am learning function pointers,I understand that we can point to functions using function pointers.Then I assume that they stay in memory.Do they stay in stack or heap?Can

相关标签:
9条回答
  • 2020-12-10 17:04

    As has been said above, function sizes are generated by the compiler at compile time, and all sizes are known to the linker at link time. If you absolutely have to, you can make the linker kick out a map file containing the starting address, the size, and of course the name. You can then parse this at runtime in your code. But I don't think there's a portable, reliable way to calculate them at runtime without overstepping the bounds of C.

    The linux kernel makes similar use of this for run-time profiling.

    0 讨论(0)
  • 2020-12-10 17:11
    #include<stdio.h>
    
    int main(){
        void demo();
        int demo2();
        void (*fun)();
        fun = demo;
        fun();
        printf("\n%lu", sizeof(demo));
        printf("\n%lu", sizeof(*fun));
        printf("\n%lu", sizeof(fun));
        printf("\n%lu", sizeof(demo2));
        return 0;
    }
    
    void demo(){
        printf("tired");    
    }
    
    int demo2(){
        printf("int type funciton\n");
        return 1;
    }
    

    hope you will get your answer, all function stored somewhere

    Here the output of the code

    above code's output

    0 讨论(0)
  • 2020-12-10 17:12

    To make it simple, functions usually don't go into the stack or the heap because they are meant to be read-only data, whereas stack and heap are read-write memories.

    Do you really need to know its size at runtime? If no, you can get it by a simple objdump -t -i .text a.out where a.out is the name of your binary. The .text is where the linker puts the code, and the loader could choose to make this memory read-only (or even just execute-only). If yes, as it has been replied in previous posts, there are ways to do it, but it's tricky and non-portable... Clifford gave the most straightforward solution, but the linker rarely puts function in such a sequential manner into the final binary. Another solution is to define sections in your linker script with pragmas, and reserve a storage for a global variable which will be filled by the linker with the SIZEOF(...) section containing your function. It's linker dependent and not all linkers provide this function.

    0 讨论(0)
提交回复
热议问题