#include <stdlib.h>
int *f1(void)
{
int x = 10;
return &x;
}
int *f2(void)
{
int *ptr;
*ptr = 10;
return ptr;
}
int *f3(void)
{
int *ptr;
ptr = malloc(sizeof *ptr);
return ptr;
}
f1和f2运用时有错误的。Function f1 returns the address of a local variable. Since the variable’s lifetime ends after the function returns, any use of the return value produces undefined behavior.
Function f2 produces undefined behavior because it dereferences and returns an uninitialized pointer. (It has not been assigned to point to anything, and its initial value is indeterminate.)
Function f3 has no errors (although its caller should make sure the return value is not NULL before using it, and call
free when the memory is no longer needed).