Returning pointer addresses from C functions requires ensuring that the referenced memory remains valid after the function returns. Returning the address of a local stack variable causes undefined behavior when the stack frame is popped.
Safe Pointer Return Using malloc()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *create_greeting(const char *name) {
// Allocate heap memory valid beyond function scope
char *buffer = malloc(128);
if (!buffer) return NULL;
snprintf(buffer, 128, "Hello, %s!", name);
return buffer;
}
int main(void) {
char *msg = create_greeting("Developer");
if (msg) {
printf("%s\n", msg);
free(msg); // Deallocate heap buffer when finished
}
return 0;
}
Comments and corrections