|
 |
CS 3723
Programming Languages
|
Dangle Example |
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
% gcc -o danglegcc dangle.c
dangle.c: In function `dangle':
dangle.c:5: warning: function returns
address of local variable
% danglegcc
Before other, p=23 <----- Stack still intact
After other, p=47 <----- Stack trashed
% CC -o dangleCC dangle.c
% dangleCC
Before other, p=23 <----- Stack still intact
After other, p=47 <----- Stack trashed
|
% cc -o nodangle nodangle.c
% nodangle
Before other, p=23 <----- Points to heap
After other, p=23 <----- Points to heap
% gcc -o nodanglegcc nodangle.c
% nodanglegcc
Before other, p=23 <----- Points to heap
After other, p=23 <----- Points to heap
% CC -o nodangleCC nodangle.c
% nodangleCC
Before other, p=23 <----- Points to heap
After other, p=23 <----- Points to heap
|
Revision date: 2014-02-25.
(Please use ISO
8601, the International Standard.)
|