CS 3723/3721 Programming Languages
|
Returning Pointers to Local Storage: Local variables in a C function are allocated on the stack when the function is called. On return from the function, the storage for these local variables is deallocated. However, this deallocated storage does not have to be physically destroyed, and the old values might still be sitting where they were. After another function call, the old storage on the stack will be overwritten with the new activation record. These issues are illustrated below.
|
It is always an error to return a pointer to local storage, though compilers do not necessarily even warn against it. |
Only the gcc compiler gave a warning in this case. Some other compilers also give warnings or errors. This kind of mistake is impossible to make in Java.
| Dangling Pointer to Local Storage | No Dangling Pointer to Local Storage |
|---|---|
/* dangle.c: dangling pointer to storage */
#include <stdio.h>
int *dangle() {
int i = 23; /* allocated on stack */
return &i; /* return ptr to stack */
}
void other() { /* mess up stack */
int i = 47;
int j = 59;
}
int main() {
int *p;
p = dangle(); /* pointer to stack */
printf("Before other, p=%i\n", *p);
other(); /* trash the stack */
printf("After other, p=%i\n", *p);
}
|
/* nodangle.c: no dangling pointer */
#include <stdio.h>
#include <stdlib.h>
int *dangle() {
int *q;
q = (int *)malloc(4); /* on heap */
*q = 23; /* points to integer */
return q; /* return ptr to heap */
}
void other() { /* mess up stack */
int i = 47;
int j = 59;
}
int main() {
int *p;
p = dangle(); /* pointer to heap */
printf("Before other, p=%i\n", *p);
other(); /* trash stack; no matter */
printf("After other, p=%i\n", *p);
}
|
| Run with C, GNU C, and C++ | Run with C, GNU C, and C++ |
% cc -o dangle dangle.c % dangle Before other, p=23 <----- Stack still intact After other, p=59 <----- Stack trashed | % cc -o nodangle nodangle.c % nodangle Before other, p=23 <----- Points to heap After other, p=23 <----- Points to heap |