简体   繁体   English

C-丢失pointe结构值

[英]C - Losing pointee struct values

**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! 因此,我想出了无论我在Data_pair_node之后执行什么操作,执行后都将重置该对象! 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 谢谢艾蒙·弗尼尔

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. 您使用整数除法(list_count和table-> bucket_ct均为整数),因此结果将被截断,并且如果平均存储桶列表长度小于1.0,则返回值为0,如果哈希表中的存储桶多于条目。

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). 很难说出是怎么回事,因为您永远不会打印出table的值或显示调用insert的代码(从那里获取它的值)。 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. table是一个本地变量,因此编译器可能会将其放在寄存器中,并在table死掉之后(在代码中的最后一次使用之后)将该寄存器重用于其他用途,在这种情况下,此时将打印table (或其他取决于table )与gdb可能会打印任何内容。

  • 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 如果table是指向堆栈的一个悬空指针(它来自另一个函数,该函数返回了局部变量的地址),则它很可能指向其他一些局部变量所用的内存,在这种情况下,分配给那些局部变量将改变table->buckets

Your problem is not the average_list_len function. 您的问题不是average_list_len函数。 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. 您的insert函数的代码显示您没有修改表的值,因此我想说在调用insert函数时您的表的存储桶为零。

You should inspect (or post?) the rest of the call stack. 您应该检查(或发布?)其余的调用堆栈。 On a side note, i recommend gdb as a nice console debugger :) 附带说明一下,我建议将gdb作为一个不错的控制台调试器:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM