It's a common problem of GDB , and already refered in its document. GDB Program Variables
As refered, it's because
on most machines, it takes more than one instruction to set up a stack frame (including local variable definitions); if you are stepping by machine instructions, variables may appear to have the wrong values until the stack frame is completely built. On exit, it usually also takes more than one machine instruction to destroy a stack frame; after you begin stepping through that group of instructions, local variable definitions may be gone.
And also the optimization level will cause impact too, but even with no optimization settings, this problem may also happen. I encoutered the same problem when I tried to debug with GDB and intentionally set no optimization.