【问题标题】:try to malloc a struct array, but get heap buffer overflow尝试 malloc 结构数组,但堆缓冲区溢出
【发布时间】:2021-08-24 07:59:02
【问题描述】:

我是编程新手,刚刚学习了 C。现在我的问题是,我试图 malloc 一个结构数组,然后用它来填写一些信息。但不断收到堆溢出错误报告。 这是我在 h.file 中声明的结构。

typedef struct llnode {
  char llnodename[256];
  int ll_index;
  struct llnode* next;
} llnode;
//the struct of a linked list.

typedef struct node_stru {
  char nodename[256];
  int node_index;
} node_stru;
//the struct of the node.

和指针:

node_stru *node_list = (struct node_stru*)malloc(n_nodenumber*(sizeof(node_stru)));

但后来当我想使用链表填写一些信息时,它给了我堆溢出。

llnode* ptr=Ahead;
while (ptr!=NULL){
  printf("the name%s, the index%d", ptr->llnodename, ptr->ll_index);
  strcpy(node_list[n_index].nodename, ptr->llnodename);
  node_list[n_index].node_index = ptr->ll_index;
  n_index++;
  ptr = ptr->next;
}

报错:我做了 malloc 一个 4*(256+4) 的内存,但还是不行。

0x619000000490 is located 0 bytes to the right of 1040-byte region [0x619000000080,0x619000000490)

【问题讨论】:

标签: c struct malloc


【解决方案1】:

您已经为node_list 分配了一个固定大小,但是没有什么可以阻止您的循环走到尽头。例如,如果n_nodenumber 为 4,您可以存储 4 个节点。但是如果Ahead 链接到 5 个节点,它将离开node_list。假设n_index 从 0 开始。

您的循环至少应该assert(n_index < n_nodenumber) 以在循环离开数组时提供更好的错误。没有看到完整的例子,我只能这么说。

【讨论】:

  • 谢谢,但是n_nodenumber是链表的结果,链表有4个节点,节点表也有4个节点需要填写。
猜你喜欢
  • 2019-07-15
  • 2010-11-11
  • 2019-07-26
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
  • 2013-07-19
相关资源
最近更新 更多