Reputation: 23
this is my student struct with the information I read in via binary
typedef struct student_t {
//data in here
} student_t;
this is how I have declared them in main
double_linkedlist_t* listPtr;
student_t students;
node_t* node = NULLL;
this is how my file is initializzed
FILE *file;
printf("What file would you like to select?\n");
fgets( filename, MAX_NAME_LENGTH, stdin );
strtok(filename, "\n");
fflush(stdin);
file = fopen(filename, "rb+wb");
This is what my fwrite looks like in my main. I keep getting a segmentation fault and all the examples that I have seen on how to write a doubly linked list to a binary file have you do this. So I come here for an explanation on why or maybe some changes to what I have. I also have my doubly linked list declared as listPtr in main, and my node as node.
this is my Init
node_t* Init_Node( student_t data )
{
node_t* node = (node_t*) malloc( sizeof( node_t ) );
node -> students = data;
node->nextPtr = NULL;
node->prevPtr = NULL;
return node;
}
this is my node struct along with the prototype to nodeinit
typedef struct node_t
{
student_t students;
struct node_t* nextPtr;
struct node_t* prevPtr;
} node_t;
//prototypes
node_t* Init_Node( student_t );
node = listPtr->headPtr; //segmentation faults here
while(node!=NULL)
{
fwrite(node, sizeof(student_t), 1, file);
node=node->nextPtr;
}
any help on why this is happening would be greatly appreciated, I have never really written to a binary file with a doubly linked list :/.
Upvotes: 0
Views: 140
Reputation: 409364
Since you don't show a more complete code, I will only be able to guess, but the problems is this:
double_linkedlist_t* listPtr;
It seems this is a local variable declared inside the main
function, and the problem with this is that local variables inside functions are not initialized. So by having the declaration and not making the pointer actually point somewhere, it will point to a seemingly random location.
Uninitialized local (non-static) variables will have an indeterminate value, and dereferencing the pointer without making it point anywhere valid will lead to undefined behavior which is a very common cause of crashes.
There are two possible solutions:
Allocate memory and make the pointer point to it:
double_linkedlist_t* listPtr = malloc(sizeof *listPtr);
Don't declare it as a pointer to begin with, and when a pointer is needed use the address-of operator &
to get one:
double_linkedlist_t list;
list.headPtr = NULL;
list.tailPtr = NULL;
...
callSomeFunction(&list);
Upvotes: 1