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!
main.NULL. What'shash? I assumenumbin theaddNumberfunction is supposed to benumber? But to answer your question, invoking undefined behavior is what causes segmentation fault sometimes.nextbefore you doptr=ptr->next;? I can't see it anywhere near malloc.