Reputation: 3331
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
createTime()
does not return NULL? The #time
is a local variable so it should be destroyed when method goes out of scope. doSomething()
I am calling createTime()
multiple times, will this create memory leak? Upvotes: 4
Views: 1720
Reputation: 134286
By saying return time;
[with the ;
], you're returning the value, not the address, and collecting that return value into the variable in the caller. The return value is simply copied into newTime
.
This is perfectly valid. There is no dynamic memory usage. There is no memory leak in this context.
Next, createTime()
cannot return NULL
, as the return type is specified as of type Time
. It has to return a valid structure variable of type Time
. Moreover, NULL
is applicable for pointer types. However, you can return a structure with all the members initialized as -1
[based on your structure definition, members are being int
] to report some failure, if you wish.
Upvotes: 3
Reputation: 141554
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:
time
inside createTime()
is created and populatedtime
time
is destroyednewTime
is created, with the return value used as initializer.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.
Upvotes: 9
Reputation: 409166
You don't return a pointer or reference, you return by value which means that the structure is copied. There's no dynamic memory allocation, it's all handled by the compiler at compilation-time, and since there's no dynamic allocation there's no chance of memory leaks.
There's one drawback to this, and that is that you can't return NULL
to indicate that there's nothing to return. You must always return a valid structure.
Upvotes: 6