Dangling Pointer Demo
C
Hard
2 views
Problem Description
Return the address of the local variable in the function. Initialize it in the function. What's the problem? Then indicate the correct reason (dynamic allocation or static variable).
Official Solution
#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;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!