|
|
|
|
|
by GorgeRonde
2545 days ago
|
|
Went to an IRC chat room when I was learning C in school. Asked if you could return a pointer to something that lives on the stack. Was talked down by an all-knowing dude telling me to go read K&R again. Proceeded to write a code sample [1] that showed it is possible (it's not really stable but works reliably in recursive calls IIRC). I do not like this attitude (then again it was just one random dude). [1] https://www.onlinegdb.com/HyO5VXRxS |
|
You might want to listen. You’re getting the K&R comment and the downvotes because this does not work, ever. It’s a really, really bad idea. In recursive calls, it might not crash right away, but you will have bad data, the memory at the pointer address will have been overwritten by the next stack frame that’s placed there.
Don’t ever return pointers to local memory because the memory is “gone” and unsafe to use the moment your function returns. Even if you try it and think it works, it can and probably will crash or run incorrectly in any other scenario - different person, different computer, different compiler, different day...
Your comments about getting a warning and ‘However if you wrap the local’s address... it “works”’ should be clues. The warning is the compiler telling you not to do it. The workaround doesn’t work, it only compiles. By using aliasing, you’re only tricking the compiler into not warning you, but the warning is there for a reason.