so got this segmentation fault every time I tried to check if a pointer variable is a NULL
. The error is from these lines of code in add function:
if (it->head == NULL){
printf("worksfine");
}
This is the whole code that I have:
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef struct Node{
int val;
struct Node *prev;
struct Node *next;
} node;
typedef struct IteratorInt{
node *head;
node *tail;
node *last;
} IteratorInt;
IteratorInt IteratorIntNew(){
IteratorInt *listint;
listint = malloc(sizeof(IteratorInt));
listint->head = NULL;
listint->tail = NULL;
listint->last = NULL;
printf("address made %u\n", listint);
return *listint;
}
int add(IteratorInt *it, int v){
node *n;
n->val = v;
n->next = NULL;
n->prev = NULL;
printf("func works\n");
printf("n %d\n", n->val);
printf("address %u", it);
it->head = n;
printf("result %d", it->head->val);
if (it->head == NULL){
printf("worksfine");
}
/* if (it->head == 0){
it->head = n;
}
if (it->tail == 0){
it->tail = n;
}
if (it->last == 0){
it->last = n;
}*/
return 1;
}
int main() {
IteratorInt lit = IteratorIntNew();
printf("works %u", &lit);
add(&lit, 10);
/*printf("Node value %d\n", lit.head.val);
add(&lit, 15);
printf("Node value %d", lit.tail.val);*/
return 0;
}
Can you tell me what's wrong with it? and how to solve that? Thanks a lot.
In your add
function, the variable n
is an uninitialized pointer. So it is not the problem of checking it->head
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments