Function returns address of a local variable.
Undefined behavior / garbage value
#include <stdio.h>
#include <stdlib.h>
/* Incorrect: returning address of local variable */
int* wrongFunction() {
int localVar = 100; // local variable on stack
return &localVar; // ❌ Dangerous!
}
/* Correct: using static variable */
int* correctStatic() {
static int staticVar = 200; // static variable persists after function ends
return &staticVar; // ✅ Safe
}
/* Correct: using dynamic allocation */
int* correctDynamic() {
int *ptr = (int *)malloc(sizeof(int)); // allocated on heap
if (ptr != NULL)
*ptr = 300;
return ptr; // ✅ Safe, must free later
}
int main() {
int *p1 = wrongFunction();
printf("Wrong function returned: %d (undefined behavior!)n", *p1);
int *p2 = correctStatic();
printf("Static variable returned: %dn", *p2);
int *p3 = correctDynamic();
printf("Dynamically allocated returned: %dn", *p3);
free(p3); // free heap memory
return 0;
}
#include <stdio.h>
#include <stdlib.h>
/* Incorrect: returning address of local variable */
int* wrongFunction() {
int localVar = 100; // local variable on stack
return &localVar; // ❌ Dangerous!
}
/* Correct: using static variable */
int* correctStatic() {
static int staticVar = 200; // static variable persists after function ends
return &staticVar; // ✅ Safe
}
/* Correct: using dynamic allocation */
int* correctDynamic() {
int *ptr = (int *)malloc(sizeof(int)); // allocated on heap
if (ptr != NULL)
*ptr = 300;
return ptr; // ✅ Safe, must free later
}
int main() {
int *p1 = wrongFunction();
printf("Wrong function returned: %d (undefined behavior!)n", *p1);
int *p2 = correctStatic();
printf("Static variable returned: %dn", *p2);
int *p3 = correctDynamic();
printf("Dynamically allocated returned: %dn", *p3);
free(p3); // free heap memory
return 0;
}