mercredi 7 octobre 2015

malloc'd char * in a struct * comes up blank somehow

I am experimenting with making a linked list in C to better understand the concept. To make it a little more interesting, I have each object with its own random string, generated by 0x41 + (rand() % 26) four times.

However, when I run the program, the strings are blank.

$ gcc ll.c && ./a.out
ID #0 = Master
ID #1 = 
ID #2 = 
...
ID #100 = 

Okay, lets run it in gdb.

$ gcc -g ll.c && gdb ./a.out
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
...
(gdb) run
Starting program: /home/braden/code/test/c/linked-list/a.out 
object 55 is: 
ID #0 = Master
ID #1 = 
...
ID #10 = 
[Inferior 1 (process 10033) exited normally]
(gdb) break main
Breakpoint 1 at 0x4008c8: file ll.c, line 73.
(gdb) run
Starting program: /home/braden/code/test/c/linked-list/a.out 

Breakpoint 1, main () at ll.c:73
73      srand(time(0));
(gdb) n
...
78          s = randstr2();
(gdb) n
79          push_thing(new_thing(s));
(gdb) print s
$1 = 0x602030 "MTBH"
(gdb) n
80          free(s);
(gdb) n
77      while(i--){
(gdb) n
78          s = randstr2();
(gdb) n
79          push_thing(new_thing(s));
(gdb) print s
$2 = 0x602030 "CWRP"

It works correctly when I step through it, making it impossible to debug what's going on here through conventional means. According to gdb and valgrind, I didn't make any mistakes.

Furthermore, I can't seem to reproduce it elsewhere. For example, placing a print statement inside the loop that creates the objects. It will print out proper strings. But when I reference them later on, they are blank.

Wait a minute...




Aucun commentaire:

Enregistrer un commentaire