简体   繁体   English

C:结构中的 GMP 指针有问题

[英]C: Trouble with GMP pointers in a struct

I'm fairly new to c and I'm implementing a DHT.对 c相当陌生,我正在实施 DHT。 For that, I have to store node IDs in a list.为此,我必须将节点 ID 存储在列表中。

Node IDs are < 2^160 whole numbers(thus resulting in me using GMP), but I'm setting 123 as an ID here to keep the example clean.节点 ID 是 < 2^160 整数(因此导致我使用 GMP),但我在这里将 123 设置为 ID 以保持示例清洁。

I am able to set the Node's ID just fine, and I also verify it with mpz_out_str .我可以很好地设置节点的 ID,我还使用mpz_out_str验证它。 When I iterate over it with g_slist_foreach and print the ID, it outputs a HUGE number, which is completely irrelevant.当我用g_slist_foreach迭代它并打印 ID 时,它会输出一个巨大的数字,这完全不相关。

I suspect it has something to do with the cast from gpointer to Node , or that I may be storing it incorrectly(very new to pointers )怀疑它与从gpointerNode的转换有关,或者我可能存储不正确(对指针来说非常新
Code:代码:

#include <glib.h>
#include <gmp.h>
#include <stdio.h>

typedef struct {
  mpz_t *node_id;
} Node;

void print_iterator(gpointer item, gpointer prefix) {
  // Also, since the item is of type gpointer,
  // It has to be casted back to Node.
  Node *node = (Node *)item;
  // outputs a HUGE, completely random number.
  mpz_out_str(stdout, 10, node->node_id);
  printf("\n");
};

GSList *add_node(GSList *nodes) {
  Node *node = malloc(sizeof(Node));
  mpz_t id;
  mpz_init(id);
  char *f = "123";
  mpz_set_str(id, f, 10);
  node->node_id = &id;
  // prints correct value
  mpz_out_str(stdout, 10, node->node_id);
  nodes = g_slist_append(nodes, node);
  return nodes;
}

int main(int argc, char const *argv[]) {
  GSList *nodes = NULL;
  nodes = add_node(nodes);
  g_slist_foreach(nodes, print_iterator, "‑‑>");
  return 0;
}

Relevant links:相关链接:

https://developer.gnome.org/glib/stable/glib-Singly-Linked-Lists.html https://developer.gnome.org/glib/stable/glib-Singly-Linked-Lists.html
https://gmplib.org/manual/ https://gmplib.org/manual/

With node->node_id = &id;使用node->node_id = &id; your node_id points at a local variable.你的 node_id 指向一个局部变量。 When add_node returns, id is destroyed and your pointer is dangling.add_node返回时, id被销毁并且您的指针悬空。 Dereferencing it results in Undefined Behavior.取消引用它会导致未定义的行为。

A simple solution is to store the id in Node rather than storing a pointer to it.一个简单的解决方案是将 id 存储在Node中,而不是存储指向它的指针。

typedef struct {
  mpz_t node_id;
} Node;

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

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