简体   繁体   中英

Segmentation fault using malloc/struct

I am trying to code an easy list in C, which is able to store numbers.
With number SIZE , an index will be calculated and the numbers have to be stored in a kind of linear list at the array index.
However, sometimes I get a "segmentation fault", like 2 of 10 tries the output is correct.
I've gone a long search, but I couldn't find the problem.
Please keep in mind that my "solution" isn't implemented fully, so currently it's only working when the calculated index has no pointer thats stored. (Couldn't continue to code because of the error.)

Here is my code:

#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;
}

What causes the "segmentation fault" sometimes? I appreciate any kind of help, thanks in advance!

Just after malloc you do init one member.

node->number = number;

But you do not init the other member, there is no

node->next = NULL;

Also, in your loop condition inside print() , you check ptr against NULL, but that is in most of the looping the non-initialised ptr->next from previous loop.

ptr = ptr->next;

Ie you rely on it to be initialised to NULL.
That is probably causing the segfault.

Useful background, as pointed out by yano (thanks):
Malloc doesn't initialize memory to 0. In order to do that you can malloc followed by a memset or you can use calloc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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