C - Losing pointee struct values

485 views Asked by At

**Updated. Sorry to those whose answers no longer make sense.

So I figured out that no matter what I put on the line after Data_pair_node, after it executes, thats when the thing is reset! WTH? :

int insert(Table *t, const char *key, const char *val){
 int dest_bucket_index;
 Table *table = t;
 Hash_bucket *dest_bucket = NULL;
 Data_pair_node *current = NULL, *prev = NULL, *new_item = NULL;

 printf("gonna be zero now");

Lo and behold:

$23 = (Hash_bucket *) 0x834010
(gdb) step
109  printf("gonna be zero now");
(gdb) print table->buckets
$24 = (Hash_bucket *) 0x0

Thanks Aymon Fournier

2

There are 2 answers

1
Chris Dodd On BEST ANSWER

You're using an integer divide (both list_count and table->bucket_ct are ints), so your result will be truncated and you'll get a return value of 0 if the average bucket list length is less than 1.0 -- if you have more buckets in the hash table than entries.

Since you want a double answer, it makes more sense to use a double divide:

ret = (double)list_count / table->bucket_ct;

edit

It's tough to tell what's going on as you never print out the value of table or show the code that calls insert (which is where it gets its value). But a couple of things might be going on.

  • table is a local var so the compiler might put it in a register and reuse that register for something else once table is dead (after the last use in the code), in which case printing table at that point (or anything depending on it) with gdb might print anything.

  • if table is a dangling pointer into the stack (it comes from another function that returned the address of a local variable), it might well be pointing at memory used for some other local vars, in which case assigning to those local vars will change the value of table->buckets

1
mcabral On

Your problem is not the average_list_len function. The only way for it to return zero is if the table has zero buckets to begin with.

Your insert function's code shows you don't modify the values of the table, so i'd say your table has zero buckets at the time the insert function is called.

You should inspect (or post?) the rest of the call stack. On a side note, i recommend gdb as a nice console debugger :)