Where does function store in memory

I have this code:

1
2
3
4
5
6
7
8
9
10
11
#include<iostream>
void print_number()
{
    int i=13579;
    std::cout<<i;
}
int main()
{
    std::cout<<(int *)&print_number;
    system("pause");
}

Address of print_number in my PC is 0x401630. Where does this address store in memory? Code, Data, BSS, Stack or Heap?
Thanks for help!
Last edited on
Based on my c++ experience with arrays and pointers. This is what I know.

There is a stack that has memory locations which we can refer to by the index i (e.g., i = 0 or 1).

The free memory locations are reffered to as heap. Any time you add an element, it goes on top of the stack, and again, and again.

Thus, the answer to your question would be that the integer i is holding a value at an address which is stored in the heap that is part of the stack.

I hope this helped.
Last edited on
> (int *)&print_number
> Address of print_number in my PC is 0x401630

Theory:
0x401630 is the human readable representation of the value of the pointer to int (the result of the explicit conversion from the function pointer to the object pointer type). The meaning of such a conversion (if supported by the implementation) is implementation-defined.

The only requirement that the standard makes is that if this conversion is supported, then the conversion of the result in the reverse direction should yield the original value. ie. if this compiles cleanly, (int*)&print_number
then ( void(*)() )(int*)&print_number must yield &print_number

In practice:
0x401630 typically is the address in some portion of storage (with at least execute access) starting from where the code for the function resides. For historical reasons, in many implementations, this is a section (aka segment) of memory with the name .text or .TEXT
Thanks to Kourosh23 and JLBorges.
the actual location varies by OS. Its in the big pile of memory allocated to the process by the OS. That memory can be divided into the classes you mention. The stack typically has global variables, function parameters and variables and calling function data so it can pop back to where it was, its called a stack for a reason. Code binary is the code segment. The heap is the whole thing, really, all the process's memory combined if I remember correctly (rarely use the term). Youll have to poke at the stack if you do any in-line assembly language. Most of the rest of it is behind the scenes unless writing an OS or driver or other low level things.

Its been a long time, but if you want to know about this stuff, study assembly language. It explicitly taps the memory locations and you have to unravel what goes where.

Last edited on
Topic archived. No new replies allowed.