c - 使用 malloc/struct 的段错误

标签 c struct malloc

我正在尝试用 C 编写一个简单的列表,它能够存储数字。
对于数字 SIZE,将计算一个索引,并且数字必须存储在数组索引处的一种线性列表中。
但是,有时我会遇到“段错误”,例如 10 次尝试中有 2 次输出正确。
我进行了长时间的搜索,但找不到问题所在。
请记住,我的“解决方案”并未完全实现,因此目前它仅在计算出的索引没有存储指针时才有效。 (由于错误无法继续编码。)

这是我的代码:

#define SIZE 3
#define NULL 0

typedef struct node_s node_t;

struct node_s {
  node_t* next;
  int number;
};

static node_t nodeArray[SIZE];

int addNumber(int numb){
  int index = number % SIZE;
  if(nodeArray[index].next == NULL){
    node_t* node = (node_t*) malloc(sizeof(node_t));
    node->number = number;
    nodeArray[hash].next = node;
  }
}

void print(){
  for(int i = 0; i < SIZE; i++){
    node_t* ptr = nodeArray[i].next;
    while(ptr != NULL){
      printf("%d -> ", ptr->number);
      ptr = ptr->next;
    }
    printf("\n");
  }
}

#include "dictionary.h"
#include <stdio.h>

int main(){
  insert(1);
  insert(2);
  print();
  return 0;
}

有时是什么导致“段错误”? 感谢任何形式的帮助,在此先感谢!

最佳答案

在 malloc 之后,您会初始化一个成员。

node->number = number;

但是你不初始化其他成员,就没有

node->next = NULL;

此外,在 print() 内的循环条件中,您检查 ptr 是否为 NULL,但这是在大多数循环中未初始化的 ptr->next from previous loop。

ptr = ptr->next;

即你依赖它被初始化为 NULL。
这可能是导致段错误的原因。

有用的背景,正如 yano 所指出的(感谢):
Malloc 不会将内存初始化为 0。为此,您可以在 malloc 后跟一个 memset,也可以使用 calloc。

关于c - 使用 malloc/struct 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47313404/

相关文章:

C 结构体分配给结构体数组

json - Golang 将 json 映射到结构

c - 将内存释放到C中的二维数组

c - 使用递归插入和删除堆栈 ADT 的元素

c - 设置后如何更改 char * const 的内容 (C)

c - 制作一个简单的HTTP网络服务器,使用errno回复 "403 Forbidden",然后重定向到403页面?

c - 为什么 malloc 不能与 strcpy 一起使用?

c - 在 switch block 中声明的变量

python - 如何在 Python 3 中交换两对字节

c - 是否可以通过分配内存来恢复 secret 数据(例如用于解密的空闲内存中的 RSA 私钥)?