1

My code is about ordered insertion in linked list & I don't understand where the ambiguity lies. But when I run the program it SEEMS to be working fine. Is it the compiler's fault or mine? I am new in this so please help me out.

#include<stdio.h>
#include<stdlib.h>
struct node{
int i;
struct node *link;
};
int main()
{
struct node *head,*p,*temp,*q;
int data;
char c;
printf("Do you want to enter data? Y/N");
scanf(" %c",&c);
fflush(stdin);
if((c=='Y')||(c=='y'))
 {
   head=(struct node*)malloc(sizeof(struct node));
   printf("Enter the data: ");
   scanf(" %d",&data);
   head->i=data;
   head->link=NULL;
 }
printf("Do you wan to enter more data? Y/N");
scanf(" %c",&c);
fflush(stdin);
q=head;
while((c=='y')||(c=='Y'))
 {
   printf("Enter the data: ");
   scanf(" %d",&data);
   temp=(struct node *)malloc(sizeof(struct node));
   temp->i=data;
   temp->link=NULL;
   if(q->i>=temp->i)
      {
        temp->link=q;
        head=temp;
      }
   else
      {
        while((q->link!=NULL)&&(temp->i>q->link->i))
           {
             q=q->link;
           }
        temp->link=q->link;
        q->link=temp;
      }
              q=head;
     fflush(stdin);
     printf("Do you want to enter more data? Y/N");
     scanf(" %c",&c);
 }
    p=head;
  while(p!=NULL)
     {
       printf("%d ",p->i);
       p=p->link;
     }
  return 0;
 }
  • 2
    Welcome to Stack Overflow! Standard warning: [Do not cast the result of malloc](http://stackoverflow.com/q/605845/1151654) – Eregrith Jun 22 '15 at 07:16
  • 2
    `fflush(stdin);` is undefined behaviour. – Sourav Ghosh Jun 22 '15 at 07:27
  • @Sourav how is it undefined? –  Jun 22 '15 at 07:52
  • This feels more like a valgrind bug than a problem. In your code. Which version of valgrind and gcc are you using? – Roberto Attias Jun 22 '15 at 07:52
  • @Roberto it is valgrind-3.9.0 & gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9) –  Jun 22 '15 at 07:55
  • @user5034652 what you mean by "how"? If you meant "why" instead, please look at the [man page](http://linux.die.net/man/3/fflush) _"The standards do not specify the behaviour for input streams."_ – Sourav Ghosh Jun 22 '15 at 07:55
  • I'd check this to see if any of the illegal instruction bug fixed in 3.10 matches your architecture: https://www.google.com/url?sa=t&source=web&rct=j&ei=IcCHVfGDOMfcoAS3vY6ICQ&url=http://valgrind.org/docs/manual/dist.news.html&ved=0CCQQFjAC&usg=AFQjCNEknab8QI2Xee9unjRY3vtMng-xjQ&sig2=UgSJz0teJUmyNkuVmC7BjA – Roberto Attias Jun 22 '15 at 08:01
  • @Sourav Ghosh Somehow it is showing segmentation fault and I point out where is it happening. –  Jun 22 '15 at 21:58

0 Answers0