Member-only story
🔄 Returning a Pointer to a Local Variable : C/C++ 🆚 Java ☕
4 min readJan 31, 2025
⚠️ ️One of the classic pitfalls in C/C++ programming is returning a pointer to a local variable.
At first glance, it may seem trivial to store a computed value in a local array and then return a pointer to it. But as soon as that function ends, the local variable goes out of scope 🚫. This can lead to undefined behavior, ranging from printing garbage characters to crashing 💥 your program altogether.
In this post, we’ll walk through:
- A buggy version of a C++ program returning a pointer to a local array.
- A corrected C++ version that avoids undefined behavior by dynamically allocating memory on the heap.
- An equivalent Java code snippet, showing how memory management in Java sidesteps this particular issue.
Finally, we’ll look at the expected outputs of these snippets and discuss why they differ.
🚨 The Buggy C++ Code
#include <stdio.h>
#include <string.h>
#include <time.h>
char* get_date()
{
char buf[80];
time_t now = time(0);
strcpy(buf, ctime(&now));
return buf; // Returning pointer to a local stack array
}
int main(int argc, char *argv[])
{
char *date = get_date();
printf("date=%s\n", date);
return 0;
}