Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return struct from a function and memory allocation

Tags:

c++

c

Lets consider such example:

typedef struct {
  int hours;
  int minutes;
  int seconds; 
} Time;

Time createTime() {
    Time time;
    time.hours = ....
    time.hours = ....
    time.hours = ....
    return time
}

void doSomething(){

    while(true){
        Time newTime = createTime(); 
        // do something with time....
    }
}

I have few questions about memory allocation

  1. Why method createTime() does not return NULL? The #time is a local variable so it should be destroyed when method goes out of scope.
  2. Inside method doSomething() I am calling createTime() multiple times, will this create memory leak?
like image 363
Maciej Miklas Avatar asked Dec 02 '22 15:12

Maciej Miklas


1 Answers

createTime cannot do return NULL; - it returns a Time.

Functions return by value in C and C++. This means that when you write return time;, there is a temporary object created called the return value. This is copied from the expression you return. In C this is member-wise copy, in C++ it uses the copy-constructor. So the sequence of events for the code Time newTime = createTime(); is:

  1. time inside createTime() is created and populated
  2. The return value is created, and has its values copied from time
  3. time is destroyed
  4. newTime is created, with the return value used as initializer.
  5. The return value is destroyed

Now this is in principle a lot of copying and destroying, but the compiler is permitted to optimize it (in both C and C++) so that the end result is that createTime can construct time directly into the memory space of newTime, with no temporaries needed. In practice you may find various levels of optimization applied.

NB. In C++11 replace copy with copy or move in the above.

like image 51
M.M Avatar answered Dec 25 '22 16:12

M.M