【发布时间】:2017-12-11 00:42:02
【问题描述】:
所以每次我尝试检查指针变量是否为NULL 时都会出现此分段错误。错误来自 add 函数中的这些代码行:
if (it->head == NULL){
printf("worksfine");
}
这是我拥有的全部代码:
#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;
}
你能告诉我它有什么问题吗?以及如何解决?非常感谢。
【问题讨论】:
-
很可能:
it为 NULL,您无法访问NULL->head。竖起大拇指调试足以找到有问题的行! -
是的,你没有分配
it... -
@John3136,但如果我删除 if 语句。它上面的 printf 语句导致
it->head工作正常。 -
@little_birdie,但是在上面的
IteratorIntNew函数中,我给它分配了一块内存。不一样吗? -
@John3136,是的,我昨天才意识到这一点。我需要返回一个指针,对吧?要么我将其更改为函数指针,要么将数据类型更改为指针数据类型。无论如何,感谢您的解释。
标签: c segmentation-fault