Dangling Pointers and Garbage Memory
Dangling Pointers and Garbage Memory
●
A pointer becomes non dangling, when assigned to a
“good” memory location like local variables, global
variables, malloc-ed memory
●
A pointer can become dangling again due to mistakes in
pointer arithmetic
Mistakes in manipulation of dynamically allocated
●
etc
Dangling Pointers
Ø
Total 3 Possibilities for a pointer value
Ø
Points to memory owned by program
Local variables, Global Variables, Malloced Memory
Ø
= NULL
Ø
Dangling
Ø Some texts differentiate between ‘wild’ (uninitialized) and ‘dangling’
pointers
Ø
Dereferencing (that is * ) a dangling (or NULL) pointer is NOT to be done
Ø
Even if you find that dereferencing a dangling pointer “does not create
problem” in your code, it is still not to be done!
Ø
Result: The OS terminates the code giving
“Segmentation Fault”
int main() {
int *p, i, j, *q;// p,q are dangling
}
p i q j
p i q j
p I = 10 q j
p I = 10 q j
p I = 10 q j
p I = 10 q j
p I = 10 q j
p I = 10 q j
next
}
next
} next
●
Having a dangling pointer does not cause
segmentation fault
Dereferencing it causes
●
●
Having dangling pointers is not wrong, but why
have them?
Garbage ●
p was pointing to malloced memory
●
In the end p points to i
Memory ●
How to access the malloced memory now?
●
No way! It's Lost!
int *p, i; ●
It became “garbage memory”
p = malloc ●
Problems like this result in memory waste
●
Also called as Memory leak
(sizeof(int) * 4); ●
Solution
p = &i; Keep another point pointing to malloced
●
memory
i ●
p = malloc(sizeof(int) * 4);
●
q = p;
●
p = &i;
p ●
Malloced memory is available through
0 1 2 3 pointer q
Segmentation Fault
What is segmentation fault?
A program accessing an “illegal” memory location
●
●
“segmentation” comes from “memory management” concepts in
operating systems
It is ALWAYS a fault of the programmer!
●
Beware
●
●
Bad compilers may generate machine code which hide some memory
violations
●
If a programmer does illegal memory access, segmentation fault may not
occur sometimes!
–OS may “forgive” your program :-;
Some Typical Reasons for Seg-fault
Deferencing Dangling Pointers
int temp;
temp = *a;
*a = * b;
*b = temp;
}
int main() {
int m = 20, n = 30;
swap(&m, &n);
}
Incorrect Pointer Aruments -
Segfault
int i;
scanf(“%d”, i);
Scanf tries to do something like
*i = value // seg fault here
Segfault occurs in scanf, although the reason is
call to scanf
●
Note that this is basically a dangling pointer
dereference which took place inside scanf()
Guidelines to avoid segfaults
Always initialize pointers to NULL
●
This will not avoid segfaults, but may lead to early detection of a problem
●
●
gcc -Wall enables all compiler's warning messages. This option should always
be used, in order to generate better code.