【发布时间】:2018-05-07 16:39:33
【问题描述】:
#include<stdio.h>
#include<malloc.h>
typedef struct nde{
int data;
struct nde *next;
}node,*pnode;
void inst_beg(node *,int);
void inst_end(node *,int);
void inst_any(node *,int,int);
int del_begin(node *);
int del_end(node *);
int del_any(node*,int);
void display(node *);
main()
{
pnode head= (node *)malloc(1*sizeof(node));
head->data=0;
head->next=NULL;
inst_any(head,1,1);
inst_any(head,2,2);
// inst_any(head,3,3);
display(head);
}
void inst_any(node *head,int pos, int data){
pnode nd=(node *)malloc(1*sizeof(node));
nd->data=data;
//pnode count=(node *)malloc(1*sizeof(node));
pnode count;
count=head;
printf("head: %p",head);
printf("count: %p",count);
int i=0;
while(i<pos-1){
count=count->next; //Problem is here for inst_any(phead,2,2)
}
nd->next=count->next;
count->next=nd;
//printf("done");
}
void display(node * head){
pnode count=head;
while(count->next!=NULL){
printf("%d",count->data);
count=count->next;
}
}
count 的值在循环内变为 null,因此当第二次调用 inst_any(head,2,2) 时,我们无法尊重它。使用 gdb 检查第一次计数是否成功指向头部。同样的情况也第二次发生。在 count=head 之后,它第二次给出正确的值。不知道之后发生了什么。为什么当它进入循环计数的值变为零时。
【问题讨论】:
-
除了我的回答,为避免以后发生此类事情,请阅读How to debug small programs。 “橡皮鸭调试”会话应该已经解决了这个错误。
-
嗨,Subhabrata,请检查下面我的答案并更正您的代码。还请阅读以下代码中的所有 cmets。
-
该函数有两个有效签名:
main()1)int main( void )和 2)int main( int argc, char *argv[] )I.E.发布的代码使用了无效的签名。 -
在调用任何堆分配函数时:(malloc, calloc, realloc) 1) 始终检查 (!=NULL) 返回值以确保操作成功。 2)返回的类型是
void*,可以分配给任何指针。强制转换只会使代码混乱,使其更难以理解、调试等。注意:将任何大小乘以 1 绝对没有效果。 -
@user3629249 实现定义的
main()签名也是“有效的”,但当然不能移植。
标签: c pointers linked-list segmentation-fault