用malloc分配了地址的指针什么情况下会是空指针?在做链表练习题时注意到答案代码里有多处出现形如以下的地方
*L = (GoodsList*)malloc(sizeof(GoodsList));
if (*L == NULL) {
return;
}
感觉是一种防出错的机制,但我很好奇空指针也可以分配地址吗?为什么不把if语句提前到分配地址的语句前呢?
提前感谢解答!这里附上整段代码
void init_list(GoodsList** L)
{
GoodsList* p;
int i = 0;
//这里出现了一次
*L = (GoodsList*)malloc(sizeof(GoodsList));
if (*L == NULL) {
return;
}
GoodsList* hpead = *L;
GoodsInfo gi;
FILE* fp = fopen("goodsinfo.txt", "a+");
if (fp == NULL) {
perror("fopen()");
return;
}
while (fscanf(fp, "%s %s %d %s %d %d\n", gi.goods_id, gi.goods_name, &gi.goods_price, gi.goods_discount, &gi.goods_amount, &gi.goods_remain) != EOF) {
//这里又出现一次
GoodsList* cur = (GoodsList*)malloc(sizeof(GoodsList));
if (cur == NULL) {
continue;
}
cur->data = gi;
hpead->next = cur;
hpead = hpead->next;
i++;
}
printf("目前有 %d个商品信息 ", i);
}