I have been professionally coding in C for a while but am still stumped by some pointer related questions. I would really appreciate SO community's help in understanding below problem.
Following code crashed and generated core file.
void func1() // Frame 1 in GDB stack trace.
{
UTYPE *ptr; // pointer to user defined type
...
// data is of type UTYPE and has valid contents.
// lets say its address is 0x100
ptr = &data; --- (1)
...
func2(ptr); --- (2)
...
}
void func2(UTYPE *inp) // Frame 0 in GDB stack trace.
{
if(!inp) --- (3)
return;
...
// another_ptr is of UTYPE * which is a NULL.
inp = another_ptr; ---- (4)
/* Did not check for NULL and dereference inp and CRASH */ ---- (5)
}
Simplified backtrace from GDB:
Frame 0:
func2(inp = 0x0)
// crash at line (5) due to dereference
Frame 1:
func1: func2(0x0)
// `ptr` at line (2) is 0x0. Why is this so?
Why is ptr
shown as 0x0 (NULL)
in Frame 1?
When func2()
is called, its call stack looks as follows:
| //local vars |
| |
| another_ptr = |
| NULL |
+---------------+
| return addr |
+---------------+
| input args |
| copy of ptr |
| contents |
| 0x100 |
For func1()
, its call stack should look like:
| |
| ptr = 0x100 |
| |
+---------------+
| return addr |
+---------------+
| input args |
| none in this |
| func |
When inp
becomes NULL
in func2()
in line (4), how is it reflected in func1()?