C++: returning pointer to local variable | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C++: returning pointer to local variable

Why is it bad practice to return a pointer to a local, non static variable?

6th Apr 2017, 5:12 PM
Jakob Robert
Jakob Robert - avatar
2 Answers
+ 1
i only want to make clear that this is an obviously attempt to get the self learner badge. i really have no idea how to get this badge, but i don't think you will be successful with this try. good luck
7th Apr 2017, 9:13 AM
Peter
0
Local, non static variables use the auto storage class. this means, the memory is allocated on the stack and is freed when the surrounding code block is left. When the function returns, the variable the pointer points to is freed from the stack. If the returned pointer is accessed, it may be, that the old value still exists in memory, but as well it may be overwritten. Actually, in this way some part of memory could be accessed that now has a completely different meaning and this can cause very ugly and hard to find bugs. So remember: Never return a pointer to a local variable. However, if you declare it on the heap, eg int *p = new int; *p = 42; return p; the pointer is still valid because memory allocated on the heap is not automatically freed. but this also means it is the caller's duty to free it when he does not need it anymore
6th Apr 2017, 5:20 PM
Jakob Robert
Jakob Robert - avatar