Returning pointer to local variable
we should avoid returning a pointer to local variable. If one wants to do that then either variable has to be declared static or varable has to be allocated dynamically. In later case calling function should take care of deallocating the variable to avoid memory leaks.
Can anyone tell me why it works in case of dynamically allocation and static declaration and why not in case of simple local variable?
Re: Returning pointer to local variable
As soon as the scope of the function ends i.e after the closing brace } of function, memory allocated(on stack) for all the local variables will be released automatically by compiler. So, returning pointer to some memory which is no longer valid invokes undefined behavior.
Whereas dynamic memory allocation is on heap/free store and memory allocated from it won't be released by the compiler. If you have allocated something dynamically then you have to deallocate it yourself when memory is no longer required otherwise there will be a memory leak.
As far as statics are concerned, memory for them is allocated from a special static/global area as soon as the program starts. This memory is released as soon as the programs gets over.
So, returning pointers on both the latter cases makes sense.
|All times are GMT +5.5. The time now is 08:49.|