Thread: runtime error in code

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    13

    runtime error in code

    Hi, I wrote this code and I don't seem to get why it gives me a runtime error...
    Any help in the matter will be much apreciated.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct node
    {
    	int info;
    	struct node * next;
    }*listptr;
    
    
    
    void print(listptr list)
    {
    	listptr p;
    	p=list;
    	while (p)
    	{
    		printf("%d ",p->info);
    		p=p->next;
    	}
    	
    }
    
    
    
    void push(struct node **s,int x)
    {
    	struct node *q;
    	q=(struct node *)malloc(sizeof(struct node));
    	q->info=x;
    	q->next=*s;
    	*s=q;
    }
    
    
    
    void main()
    {
    	int n;
    	listptr list;
    
    	scanf("%d",&n);
    	
    	while (n!=999)
    	{
    		push(&list,n);
    		scanf("%d",&n);
    	}
    	print(list);
    }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Looks like you never set a next element to NULL, so you have to end of your list. If you initialize list to NULL in main, the first time you call push, it will set q->next to NULL.

  3. #3
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Also:

    1) Don't cast malloc.

    2)void main() should be int main(void) and return 0.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  4. #4
    Registered User
    Join Date
    Nov 2010
    Posts
    13
    Thankies :3 NULL does the job!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Proposal: Code colouring
    By Perspective in forum A Brief History of Cprogramming.com
    Replies: 28
    Last Post: 05-14-2007, 07:23 AM
  2. Updated sound engine code
    By VirtualAce in forum Game Programming
    Replies: 8
    Last Post: 11-18-2004, 12:38 PM
  3. Executing C++ Code at Runtime
    By jdm in forum C++ Programming
    Replies: 14
    Last Post: 10-18-2004, 05:32 PM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. Replies: 4
    Last Post: 01-16-2002, 12:04 AM