指针导致的段错误

创建链表发生段错误,通过gdb定位到 *L =(Linklist)malloc(sizeof(node))这句有问题,发现穿件Linklist *L时其实是struct node **L;向函数传入L其实传入的是空地址或者是随机地址,
*L应该不存在,但是通过打印又打印出了地址:


Linklist *l;
printf("data:%x,point:%x\n",l,&l);
printf("data:%x,point:%x\n",*l,&*l);
printf("data:node,point:%x\n",&**l);

data:b77a9280,point:bfe20290
data:57e58955,point:b77a9280
data:node,point:57e58955

在后面加上一个return 0;打印内容又不一样:

Linklist *l;
printf("data:%x,point:%x\n",l,&l);
printf("data:%x,point:%x\n",*l,&*l);
printf("data:node,point:%x\n",&**l);
return 0;

data:0,point:bfa60714
Segmentation fault (core dumped)

此时的l的值为空,并且*l不存在发生了段错误。

 

linked.h:

//定义节点数据的类型
typedef int Elemtype;

//创建node结构体
struct node
{
Elemtype data;
struct node * next;
}node;

//定义链表
typedef struct node * Linklist;
//定义返回状态
typedef int Status;
//创建链表
Status CreateListHead(Linklist *L,int n);
//链表插入数据
Status Listinsert(Linklist *L,int n,Elemtype e);
//链表删除数据
Status ListDel(Linklist *L,int n);
//打印链表
void ListPrintf(Linklist *L);



linked.c:

#include <stdlib.h> #include <stdio.h> #include <time.h> #include "linked.h" int main() { Linklist *l; Elemtype data; int Num,status; printf("enter you need number node of link list\n"); scanf("%d",&Num); status=CreateListHead(l,Num); if(status) { printf("creat error!"); } printf("1.insert you node !\n2.del you node !\n3.printf you list!\n4.quit\n"); while(scanf("%d",&Num)==1) { switch(Num) { case 1: { printf("enter data and num:\n"); scanf("%d,%d",&data,&Num); Listinsert(l,Num,data); } break; case 2: { printf("enter you del num:\n"); scanf("%d",&Num); ListDel(l,Num); } break; case 3: { ListPrintf(l); } break; case 4: return 0; break; } printf("1.insert you node !\n2.del you node !\n3.printf you list!\n4.quit\n"); } } Status CreateListHead(Linklist *L,int n) { int i=0; Linklist p; srand(time(NULL)); *L =(Linklist)malloc(sizeof(node)); (*L)->next=NULL; for(i;i<n;i++) { p = (Linklist)malloc(sizeof(node)); p->data = rand()%100 + 1; p->next = (*L)->next; (*L)->next = p; } return 0; }
posted @ 2018-03-30 14:49  破壁Zr  阅读(300)  评论(0编辑  收藏  举报