使用malloc/struct进行分段错误

Tja*_*tte 0 c malloc struct

我试图在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;
}
Run Code Online (Sandbox Code Playgroud)

什么原因导致"分段错误"?我感谢任何帮助,提前谢谢!

Yun*_*sch 5

在malloc之后,你做一个成员.

node->number = number;
Run Code Online (Sandbox Code Playgroud)

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

node->next = NULL;
Run Code Online (Sandbox Code Playgroud)

另外,在你的循环条件里面print(),你检查ptr是否为NULL,但这是在大多数循环中非初始化的ptr->接下来的前一个循环.

ptr = ptr->next;
Run Code Online (Sandbox Code Playgroud)

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

有用的背景,正如yano所指出的那样(谢谢):
Malloc没有将内存初始化为0.为了做到这一点你可以使用malloc后跟memset,或者你可以使用calloc.

  • @Tjatte不,`malloc`没有将内存初始化为0.为了做到这一点你可以`malloc`后跟一个[`memset`](https://linux.die.net/man/3/memset)或者你可以使用[`calloc`](https://linux.die.net/man/3/calloc) (2认同)