Search code examples
cgdbgnu

Can the C language forget a variable?


It sounds very weird, but I noticed that my program crashes because a variable is literally forgotten (turning to 0).

This is the output of gdb

...
709         while (progressione->avanti !=  NULL) {
(gdb) p nGiocatori 
$30 = 4
(gdb) step
713         lista_stanze[i] = *progressione; // aggiungo la stanza alla 
lista
(gdb) p nGiocatori 
$31 = 4
(gdb) step
731         puts("");
(gdb) p nGiocatori 
$32 = 0
(gdb) 

as you can see after puts("") the value of nGiocatori is turned to 0. The problem is not related to puts("") whatever statement in replace of puts("") causes the same problem.

Can anyone explain to me why this strange thing happens?

(I don't know if it matters or not, but the variable nGiocatori is global and static unsigned short, its value is taken through scanf.)


Solution

  • I noticed that my program crashes because a variable is literally forgotten

    It's not "forgotten" it's overwritten.

    Sounds like you have a global buffer overflow in your program. Several general approaches can help you:

    • turn on all compiler warnings and make sure your code doesn't produce any (for GCC, use -Wall -Wextra -Werror)
    • build your program with address sanitizer (gcc -fsanitize=address ...)
    • set a GDB watchpoint on the variable, and observe where exactly it is being overwritten