What happens on function return to what's been stored in stack memory?

Hello everyone,

I have done my research but could not find an answer to this question I have. It might be due to lack of my bad phrasing of queries, so I beg your pardon in advance if this has been answered elsewhere but I would like to understand this very much.

Inside my main function, if I create an integer with:

int myInt;

to store an integer, and then call a predefined function (myFunc) with:

myInt = myFunc();

1
2
3
4
5
6
7
8
9
10
11
12
13
int myFunc () {

    int calculatedInt;

/* some important calculations
   are calculated and ran here to
   be stored in calculatedInt */

    calculatedInt = 8; // as an example.

    return calculatedInt;

}



My question:

 - What exactly happens in computers memory?

 - Does it store "8" in an address, then copy it
to another address and delete first one?
(since it falls out of scope after function terminates)

 - Or does it store it once, in a single address, and
returns a pointer to it under the hood as if I had a
function that returns a pointer to an object
created inside the function via "new" keyword?


ex:

1
2
3
4
5
6
7
8
9
10
int* myFunc () {

    int* calculatedInt = new int;

    // .... .... ...

    // Return the pointer pointing to a what calculatedInt points to.
    return calculatedInt;

}

In above scenario calculatedInt the pointer is stored in "stack", and only once does a new int is created and stored in heap permenantly, and its address gets returned so if my above myInt was a pointer, it would be pointed to that.

Or am I wrong?

Can you please compare the two scenarios?
Last edited on
Returning by value, as in int myFunc () returns a copy of an object (a copy of calculatedInt in the example).

Returning a pointer by value, as in int* myFunc () returns a copy of an address (a copy of the pointer calculatedInt in the example).

In either case, each time the function is called, a fresh copy is returned.
JLBorges,

Am I correct understand that a copy means that the same value is copied to a new memory address and that's what's returned?

Thank you.
not every value has an address. That function just retuns the value
(try compiling int* p = &myFunct(); or even int* p = &42; )
Last edited on
Usually object code uses registers (more often register EAX or register pair EAX:EDX for Intel compatible processors) to return objects of such simple types as int or int *. So the object code simply stores the values in register in the memory occupied by the variable that is assigned to.
Thank you very much all.
Topic archived. No new replies allowed.