Lettura da file con allocazione in una lista

di il
36 risposte

Lettura da file con allocazione in una lista

Salve a tutti,
ho un problema con un programma che gestisce un magazino di ricambi. Io per adesso lo sto provando solo con interi, perchè ancora non ho assimilato bene la funzione che permette di scrivere dentro un'allocazione di memoria, una stringa. Se non sbaglio si chiama strcpy questa funzione.
Il problema per adesso sta nella lettura degli interi. Per la scrittura, ecc. ci siamo perfettamente, ma per la lettura mi da sempre un errore riguardante la segmentazione.
Potreste aiutarmi???

Vi ringrazio anticipatamente.


Ecco il codice che ho scritto:




#include <stdio.h>
#include <stdlib.h>
struct articolo{ int num;
		 struct articolo *next;		};	
typedef struct articolo nodo;
nodo *cons(nodo *start, nodo *p); 
char menu();
void stampa(nodo *start, nodo *p);
nodo *delete(nodo *start, nodo *p);
nodo *leggi(nodo *start, nodo *p);
void scrivi(nodo *start, nodo *p);

main(int argc, char **argv)
{
	char sc;
	nodo *start, *p, *punt;

	start=(nodo *)malloc(sizeof(nodo));

	p=start; 
	p->next=NULL;
do{
sc=menu(); 
switch(sc){
	case 'a': start=cons(start, p);		 break; 
	case 'd': start=delete(start, p);	 break;
	case 's': stampa(start, p);		 break;
	case 'l': start=leggi(start, p);         break;
	case 'w': scrivi(start, p); 	 	 break;
	case 'q': exit (0); }

}while(sc!='q');
}



void stampa(nodo *start, nodo *p){
	while(start!=NULL)
	{printf("%d--> ", start->num);
	 start=start->next;
				}  
	printf("\n");
				}


nodo *cons(nodo *start, nodo *p)
	{ nodo *start2;  int numero;
	  start2=(nodo *)malloc(sizeof(nodo));
	  printf("Inserisci numero: "); scanf("%d", &numero);
	  p=start2;	
	  p->num=numero;
	  p->next=start ; 
	 return (start2);
	}


char menu() 

	{char sc; printf("A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit\n");
	 scanf("%c", &sc); return (sc);	}

nodo *delete(nodo *start, nodo *p)
	{int num_del; nodo *p2; 
	 printf("Inserisci il numero che vuoi eliminare:");
	 scanf("%d", &num_del);
	 p2=start;
	 	while(p2->next->num!=num_del)
	 	{p2=p2->next;} 
	 	p2->next=p2->next->next;	
	return (start);  
							}
nodo *leggi(nodo *start, nodo *p)
	{FILE *pf; 
	 pf=fopen("numeri.txt", "r");
	 nodo *start3;
	 start3=(nodo *)malloc(sizeof(nodo)); 
	 p=start3;

	 if(pf)
		{while(!feof(pf))
			{fscanf(pf, "%d\t", &p->num); p=p->next;} 
		 fclose(pf);
		}else{printf("Errore nella lettura del file\n");}
	p->next=start;
	return(start3);	} 

void scrivi(nodo *start, nodo *p)
	{FILE *pf;
	 pf=fopen("numeri.txt", "w");
	 if(pf)
		{while(start!=NULL)
			{fprintf(pf, "%d\t", start->num); start=start->next;}
		fclose(pf);
		}else{printf("Non è stato possibile scrivere il file\n");} 
	}

36 Risposte

  • Re: Lettura da file con allocazione in una lista

    Ah dimenticavo, sto usando il linguaggio C su piattaforma UNIX (Linux Ubuntu).

    Scusatemi ma sono nuovo su questo forum, perchè è la prima volta che programmo in C.


    Vi ringrazio sempre.
  • Re: Lettura da file con allocazione in una lista

    Up
  • Re: Lettura da file con allocazione in una lista

    Il problema che segnali è discusso nel thread seguente di questo sito:
    http://www.iprogrammatori.it/forum-programmazione/cplusplus/problema-con-lista-lineare-t11343.html
    Velocemente il tuo codice potrebbe essere:
    
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct articolo {
      int num;
      struct articolo *next;
    }nodo;
    
    void cons(nodo **head)
    {
      nodo *new;
      int numero;
      
      if ((new=(nodo *)malloc(sizeof(nodo)))==NULL)
      {
        fprintf (stderr,"Cannont allocate\n");
        return ;
      }
      printf("Inserisci numero: "); scanf("%d", &numero);
      new->num=numero;
    
      new->next=*head;
      *head=new;
    }
    
    void cancella (nodo **head)
    {
      nodo *tmp=*head,*next;
      while(tmp)
      {
        next=tmp;
        free (tmp);
        tmp=(next) ? next->next : NULL;
      }
    }
    
    void stampa(nodo **head)
    {
      nodo *tmp=*head;
      while(tmp)
      {
        printf("%d--> ", tmp->num);
        tmp=tmp->next;
      }  
      printf("\n");
    }
    
    int main ()
    {
      nodo *head=NULL;
      
      cons (&head);
      cons (&head);
      cons (&head);
      
      stampa (&head);
      cancella (&head);
      return 0;
    }
    
    Ti segnalo che su piattaforma linux esiste uno strumento di analisi memoria che si chiama 'valgrind' ed un debugger 'ddd'.
  • Re: Lettura da file con allocazione in una lista

    Nell'attesa che qualcuno possa rispondermi ho modificato il codice, e in questo modo mi legge SOLO l'ultimo numero del file.

    Codice:
    
    .................
    
    nodo *leggi(nodo *start, nodo *p)
    	{FILE *pf; 
    	 pf=fopen("numeri.txt", "r");
    	nodo *start3;
    	start3=(nodo *)malloc(sizeof(nodo)); 
    	p=start3;
    
    	 if(pf)
    		{while(!feof(pf))
    			{fscanf(pf, "%d\t", &p->num);  [color=#FF0000] /* manca l'incremento, perchè se utilizzo l'incremento non c'è più nulla, infatti parte dall'ultimo numero. */ [/color]  } 
    		 fclose(pf);  
    		}else{printf("Errore nella lettura del file\n");}
    	p->next=start;
    	return(start3);	} 
    
    ...........................
  • Re: Lettura da file con allocazione in una lista

    Se qualcuno fosse interessato allego questo src x la gestione delle liste in C

    list.h
    
    /*
     * Copyright (C) 2010, Max Cavallo <ixamit@gmail.com>
     *
     * This program is free software; you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation; either version 2 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     *
    */
    
    #ifndef _LIST_H
    #define _LIST_H
    
    #define EOL             NULL
    #define LIST_FIRST       0
    #define LIST_LAST       -1
    #define LIST_CURRENT    -2
    
    #define LIST_BY_NUM      1
    #define LIST_BY_ITEM     2
    
    #define LIST_FORWARD     1
    #define LIST_BACKWARD   -1
    
    
    typedef struct itemlist
    {
      void *data;
      //unsigned int data_size;
      
      struct itemlist * next;
      struct itemlist * prev;
    }ITEMLIST;
    
    typedef struct list
    {
      unsigned int num_elem;
    
      struct itemlist * first_item;
      struct itemlist * current_item;
      struct itemlist * last_item;
    
      struct list * next;
      struct list * prev;
      
    }LIST;
    
    
    
    /*
        struct list *list_create ();
        define a new list
    */
    LIST *list_create ();
    
    
    
    /*
        list_destroy (LIST *list);
        destroy list
    */
    void list_destroy (LIST *list);
    
    
    
    /*
        struct itemlist *list_add (LIST *list, int pos, void *data);
        add a new item to list
        pos must be a valid position number from 0 to n-1 || LIST_FIRST || LIST_LAST || LIST_CURRENT
            it define the #entry 
        data -> your data
    */
    ITEMLIST *list_add (LIST *list, int pos, void *data);
    
    
    
    /*
        void list_del (LIST *list);
        delete the current item list
    */
    void list_del (LIST *list);
    
    
    
    /*
        ITEMLIST *list_findnext (struct list *list);
        search next
        return ITEMLIST || EOL
    */
    ITEMLIST *list_seeknext (LIST *list);
    
    
    
    /*
        ITEMLIST *list_findprev (struct list *list);
        search prev
        return ITEMLIST || EOL
    */
    ITEMLIST *list_seekprev (LIST *list);
    
    
    
    /*
          ITEMLIST *list_seek (LIST *list, int START, int skip, int LIST_BY,...)
          perform sequential search by LIST_BY_NUM || LIST_BY_ITEM. 
          
          START initial position record; can be LIST_FIRST || LIST_LAST || LIST_CURRENT || valid record number from 0 to n-1
          skip  rekord to skip; negative value skip back
          LIST_BY seek mode, must be LIST_BY_NUM || LIST_BY_ITEM
          
          LIST_BY_ITEM needs extra parameter; comparator function and match as below
          list_seek (struct list *list, DIRECTION, START, LIST_BY_ITEM, (*comparator) ( const void *, const void *), void *match);
          
          return ITEMLIST || EOL
          
          Some examples:
          list_seek (list, LIST_FIRST, 0, LIST_BY_NUM);  // rek 1
          list_seek (list, LIST_FIRST, 4, LIST_BY_NUM);  // rek 5
          list_seek (list, LIST_LAST , 0, LIST_BY_NUM);  // rek last
          list_seek (list, LIST_LAST ,-1, LIST_BY_NUM);  // rek last-1
          list_seek (list, LIST_CURRENT ,-2, LIST_BY_NUM);  // rek current-2
          list_seek (list, LIST_LAST,    -1, LIST_BY_ITEM,my_compare_function,&"fooname"); // starting from last 
                                                                                           // seek backward the 2^ fooname
                                                                                           
    */
    ITEMLIST *list_seek (LIST *list, int START, int skip, int LIST_BY,...);
    
    
    
    /*
          ITEMLIST *list_first (LIST *list);
          ITEMLIST *list_last (LIST *list);
          return ITEMLIST || EOL
    */
    ITEMLIST *list_first (LIST *list);
    ITEMLIST *list_last (LIST *list);
    
    
    
    /*
          ITEMLIST *list_EOL (struct list *list);
          return true || false
    */
    int list_EOL (LIST *list);
    
    
    
    /*
          ITEMLIST *list_current (struct list *list);
          return ITEMLIST || EOL
          
    */
    ITEMLIST *list_current (LIST *list);
    
    
    
    /*
          void *list_data (struct list *list);
          return (void *) || NULL
          
    */
    void *list_data (LIST *list);
    
    
    
    /*
          unsigned int list_datasize (struct list *list);
          return (unsigned int) || 0
          
    
    unsigned int list_datasize (LIST *list);
    */
    
    
    /*
          unsigned int list_num_elem (struct list *list);
          return (unsigned int) || 0
          
    */
    unsigned int list_num_elem (LIST *list);
    
    
    
    /*
          void list_swap (LIST *listA, ITEMLIST *A, LIST *listB, ITEMLIST *B);
          swap two ITEMLIST from same or different list
    */
    void list_swap (LIST *listA, ITEMLIST *A, LIST *listB, ITEMLIST *B);
    
    
    
    /*
          void list_bsort (LIST *list, int (* comparator) ( const void *, const void *));
          bubble sort
    */
    void list_bsort (LIST *list, int (* comparator) ( const void *, const void *));
    
    #endif // _LIST_H
    
    list.c
    
    /*
     * Copyright (C) 2010, Max Cavallo <ixamit@gmail.com>
     *
     * This program is free software; you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation; either version 2 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     *
    */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <stdarg.h>
    
    #include "list.h"
    
    LIST *First=NULL;
    LIST *Last =NULL;
    
    LIST *list_create ()
    {
      LIST *new;
      
      if((new=malloc (sizeof(struct list)))==NULL)
        return NULL;
    
      new->num_elem=0;
      new->first_item=NULL;
      new->current_item=NULL;
      new->last_item=NULL;
      
      new->prev=Last;
      new->next=NULL;
      if (!First) First=new;
      if (Last)	Last->next=new;
      Last=new;
      
      return (new);
    }
    
    void list_destroy (LIST *list)
    {
      ITEMLIST *next;
      
      list->current_item=list->first_item;
      while (list->current_item)
      {
        next=list->current_item->next;
        free (list->current_item);
        list->current_item=next;
      }
      
      if (list == Last )	Last =list->prev;
      if (list == First)	First=list->next;
      if (list->prev)		(list->prev)->next=list->next;
      if (list->next)		(list->next)->prev=list->prev;
    
      free (list);
    }
    
    ITEMLIST *list_add (LIST *list, int START, void *data)//, unsigned int data_size)
    {
      ITEMLIST *new,*prev,*next;
      int pos=START;
    
      if (pos == LIST_FIRST)
      {
        prev=NULL;
        next=list->first_item;
      }
      else if (pos == LIST_LAST)
      {
        prev=list->last_item;
        next=NULL;
      }
      else if (pos == LIST_CURRENT)
      {
        if (list->current_item)
        {
          prev=list->current_item;
          next=list->current_item->next;
        }
        else
        { 
          pos = LIST_LAST;
          prev=list->last_item;
          next=NULL;
        }
      }
    
      else if (pos > 0)
      {
        next=list->first_item;
        while (next && pos--)   next=next->next;
        if (next) 
          prev=next->prev;
        else
        {
          prev=list->last_item;
          pos = LIST_LAST;
        }
      }
      else
      {
        fprintf (stderr, "list_add: Warning parameter START=%d\n",pos);
        return NULL;
      }
    
      if((new=malloc (sizeof(struct itemlist)))==NULL)
        return NULL;
      
      new->data=data;
      //new->data_size=data_size;
    
      new->prev=prev;
      new->next=next;
      
      if (prev) prev->next=new;
      if (next) next->prev=new;
      
      if (!list->first_item || pos == LIST_FIRST) 
        list->first_item=new;
      if (!list->last_item || pos == LIST_LAST)  
        list->last_item=new;
      
      list->current_item=new;
      list->num_elem++;
    
      return new;
    }
    
    void list_del (LIST *list)
    {
      ITEMLIST *current_item;
      
      if (list==NULL || list->current_item==NULL)
        return; 
      
      current_item=list->current_item;
    
      if (current_item == list->last_item )	list->last_item =current_item->prev;
      if (current_item == list->first_item)	list->first_item=current_item->next;
      if (current_item->prev)		(current_item->prev)->next=current_item->next;
      if (current_item->next)		(current_item->next)->prev=current_item->prev;
    
      list->num_elem--;
      list->current_item=current_item->next;
      
      free (current_item);
    
    }
    
    ITEMLIST *list_seek (LIST *list, int START, int skip, int LIST_BY,...)
    {
      ITEMLIST *l;
      va_list va;
      int FORWARD;
      int SKIP=skip;
      int (*comparator)();
      char *match;
    
      // TODO Error Manager
      if (START!=LIST_FIRST && START!=LIST_CURRENT && START!=LIST_LAST)
        return NULL;
        
      if (LIST_BY!=LIST_BY_NUM && LIST_BY!=LIST_BY_ITEM)
        return NULL;
    
      if (START==LIST_FIRST)
        l=list->first_item;
      else if (START==LIST_CURRENT)
        l=list->current_item;
      else if (START==LIST_LAST)
        l=list->last_item;
    
      if (skip<0)  {    SKIP=skip*(-1); FORWARD=0;  }
      else         {    SKIP=skip;      FORWARD=1;  }
      
      
      if (LIST_BY==LIST_BY_NUM)
      {
        for (;SKIP;SKIP--)
        {
            l=(FORWARD) ? l->next : l->prev;
        } 
      }
     
      if (LIST_BY==LIST_BY_ITEM)
      {
        va_start(va, LIST_BY);
        
        comparator=va_arg(va,void *);
        match=va_arg(va,void *);
        
        while (l)
        {
          if ((* comparator ) (l->data,match)==0)
          {
            if (SKIP--==0)
              break;
          }
          //else
          //{
            l=(FORWARD) ? l->next : l->prev;
          //} 
        }
      }
      
      list->current_item=l;
      
      return (l);
    }
    
    
    ITEMLIST *list_seeknext (LIST *list)
    {
      list->current_item=list->current_item->next;
      return (list->current_item);
    }
    
    ITEMLIST *list_seekprev (LIST *list)
    {
      list->current_item=list->current_item->prev;
      return (list->current_item);
    }
    
    ITEMLIST *list_first (LIST *list)
    {
      return (list_seek (list, LIST_FIRST, 0, LIST_BY_NUM));
    }
    
    ITEMLIST *list_last (LIST *list)
    {
      return (list_seek (list, LIST_LAST, 0, LIST_BY_NUM));
    }
    
    int list_EOL (LIST *list)
    {
      return (list->current_item ? 0 : 1);
    }
    
    ITEMLIST *list_current (LIST *list)
    {
      return (list->current_item);
    }
    void *list_data (LIST *list)
    {
      return (list->current_item) ? list->current_item->data : NULL;
    }
    /*
    unsigned int list_datasize (LIST *list)
    {
      return (list->current_item) ? list->current_item->data_size : 0;
    }
    */
    unsigned int list_num_elem (LIST *list)
    {
      return (list->num_elem);
    }
    
    void list_swap (LIST *listA, ITEMLIST *A, LIST *listB, ITEMLIST *B)
    {
      /*
        Swap a & b. Examples poiters scheme
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
        |p0|  |  |  |p1|  |  |  |p2|  |  |  |p3| 
        |  |  |A |  |  |  |  |  |  |  |B |  |  |
        |  |  |  |  |  |  |  |  |  |  |  |  |  |
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
        |p2|  |  |  |p3|  |  |  |p0|  |  |  |p1| 
        |  |  |B |  |  |  |  |  |  |  |A |  |  |
        |  |  |  |  |  |  |  |  |  |  |  |  |  |
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
        
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
        |p0|  |  |  |p1|  |  |  |p3|  |  |  |  | 
        |  |  |A |  |p2|  |B |  |  |  |  |  |  |
        |  |  |  |  |  |  |  |  |  |  |  |  |  |
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
        |p2|  |  |  |p0|  |  |  |p1|  |  |  |  | 
        |  |  |B |  |p3|  |A |  |  |  |  |  |  |
        |  |  |  |  |  |  |  |  |  |  |  |  |  |
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
        
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
        |p0|  |p2|  |p1|  |p3|  |  |  |  |  |  | 
        |  |  |A |  |B |  |  |  |  |  |  |  |  |
        |  |  |  |  |  |  |  |  |  |  |  |  |  |
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
        |p2|  |p0|  |p3|  |p1|  |  |  |  |  |  | 
        |  |  |B |  |A |  |  |  |  |  |  |  |  |
        |  |  |  |  |  |  |  |  |  |  |  |  |  |
        +--+  +--+  +--+  +--+  +--+  +--+  +--+
      */
      
      ITEMLIST *p[4];
      int is_adjacent=0;
      
      if (A==B || A==NULL || B==NULL) return;
      if (A->next==B)  is_adjacent=1;   else if (A->prev==B) is_adjacent=2;
      
      p[0]=A->prev;
      p[1]=A->next;
      p[2]=B->prev;
      p[3]=B->next;
    
      if (p[0])     p[0]->next=B;
      if (p[1])     p[1]->prev=B;
      if (p[2])     p[2]->next=A;
      if (p[3])     p[3]->prev=A;
    
      if (p[1] && p[1]==p[2])
      {
        p[1]->next=A;
        p[2]->prev=B;
      }
      if (p[0] && p[0]==p[3])
      {
        p[0]->prev=A;
        p[3]->next=B;
      }
      
      if (is_adjacent==1)
      {
        A->prev=B;
        A->next=p[3];
        B->prev=p[0];
        B->next=A;  
      }
      else if (is_adjacent==2)
      {
        A->prev=p[2];
        A->next=B;
        B->prev=A;
        B->next=p[1];  
      }
      else
      {
        A->prev=p[2];
        A->next=p[3];
        B->prev=p[0];
        B->next=p[1];
      }
      
      if (A==listA->first_item) 
        listA->first_item=B;
      else if (B==listB->first_item) 
        listB->first_item=A;
      
      if (B==listB->last_item)  
        listB->last_item =A;
      else if (A==listA->last_item)
        listA->last_item =B;
    }
    
    void list_bsort (struct list *list, int (* comparator) ( const void *, const void *))
    {
      ITEMLIST *p1,*p2;
      int i,n;
     
      n=list_num_elem (list);
      
      while (n > 1)
      {
        p1=list->first_item;
        p2=(p1) ? p1->next : NULL;
        for (i=0;i<n-1;i++)
        {
          if ((* comparator ) (p1->data,p2->data) > 0)
          {
            list_swap (list, p1, list, p2);
            p2=(p1) ? p1->next : NULL;
          }
          else
          {
            p1=p2;
            p2=(p1) ? p1->next : NULL;
          }
        }
        n--;
      }
    }
    
    example.c
    
    /*
     * Copyright (C) 2010, Max Cavallo <ixamit@gmail.com>
     *
     * This program is free software; you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation; either version 2 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     *
    */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    //#include "timing.h"
    #include "list.h"
    
    
    /*
      ------------------------------
      ------------------------------
    */
    #define MAXNAME 32
    struct s1
    {
      char *name;
      int  ID;
    }s1;
    
    
    int sort_cmp_by_name(const void *a, const void *b)
    {
      
      struct s1 *ia = (struct s1 *)a;
      struct s1 *ib = (struct s1 *)b;
      return (int)(strcmp (ia->name,ib->name));
    } 
    
    int sort_cmp_by_ID(const void *a, const void *b)
    {
      
      struct s1 *ia = (struct s1 *)a;
      struct s1 *ib = (struct s1 *)b;
      
      return (int)(ia->ID - ib->ID);
    } 
    
    int seek_cmp_by_name(const void *a, const void *b)
    {
      
      struct s1 *ia = (struct s1 *)a;
      char *ib = (char *) b;
      
      return (int)(strcmp (ia->name,ib));
    } 
    
    int seek_cmp_by_ID(const void *a, const void *b)
    {
      
      struct s1 *ia = (struct s1 *)a;
      int *ib = (int *) b;
      
      return (ia->ID-(*ib));
    } 
    
    void show_item (LIST *list)
    {
      struct s1 *ps1;
      ps1=list_data(list);
      //
      // showing the struct
      //
      printf ("(%p)%-15s ID=%6d | \t",list->current_item,ps1->name,ps1->ID);
    }
    
    void example_insert (LIST *list)
    {
      struct s1 *ps1;
      int i;
      
      if ((ps1=malloc (sizeof(struct s1)))==NULL)
        return;
      if ((ps1->name=malloc (MAXNAME))==NULL)
      {
        free (ps1);
        return;
      }
      printf ("Insert name:");
      scanf ("%s",ps1->name);
      printf ("         ID:");
      scanf ("%d",&ps1->ID);
      printf ("Where should I put it into the list (0=First, 1=second, 2=Third ... -1=Append)");
      scanf ("%d",&i);
          
      if (!list_add (list, i , ps1))//, sizeof(struct s1)))
      {
        free (ps1->name);
        free (ps1);
      }
    }
    
    void example_load_file (LIST *list)
    {
      struct s1 *ps1;
      int i,l;
      FILE *fp;
    
      if ((fp=fopen ("./lista.txt","r"))==NULL)
      {
        printf ("File not Found!\n");
        return;
      }
      while (1)
      {
        if ((ps1=malloc (sizeof(struct s1)))==NULL)
        return;
        if ((ps1->name=malloc (MAXNAME))==NULL)
        {
          free (ps1->name);
          free (ps1);
          break;
        }
        if ((l=fscanf (fp,"%s%d",ps1->name,&i))==-1)
        {
          free (ps1->name);
          free (ps1);
          break;
        }
        ps1->ID=i;
        if (!list_add (list, LIST_LAST , ps1))//, sizeof(struct s1)))
        {
          free (ps1->name);
          free (ps1);
          break;
        }
      }
      fclose (fp);
    }
    
    void example_insert_many (LIST *list)
    {
      struct s1 *ps1;
      int i,j;
      
      for (i=0;i<500;i++)
      {
        if ((ps1=malloc (sizeof(struct s1)))==NULL)
        return;
        if ((ps1->name=malloc (MAXNAME))==NULL)
        {
          free (ps1);
          return;
        }
        
        for (j=0;j<5;j++)
          ps1->name[j]=65+rand()%25;
        
        ps1->ID=rand()%9999;
              
        if (!list_add (list, LIST_LAST , ps1))//, sizeof(struct s1)))
        {
          free (ps1->name);
          free (ps1);
        }
      }
      printf ("Done %d random items\n",i);
    }
    
    void example_delete (LIST *list)
    {
      struct s1 *ps1;
      int i;
      
      if (list_num_elem(list)==0)  
      {
        printf ("empty list\n");
        printf ("\n");
        return;
      }
      do
      {
        printf ("Witch one of %d items do u want to delete?",list_num_elem(list));
        scanf ("%d",&i);
      }while (i<0 || i>list_num_elem(list)-1);
    
      list_seek (list,LIST_FIRST, i, LIST_BY_NUM);
      ps1=list_data(list);    
      free (ps1->name);
      free (ps1);    
      list_del (list);
    }
    
    void example_sort (LIST *list)
    {
      int i;
    
      do
      {
        printf ("Sorting by 0=Name or 1=ID ?");
        scanf ("%d",&i);
      }while (i < 0 || i >2);
      
      printf ("Sorting...\n");
      //timer ();
      if (i==0)
        list_bsort (list,sort_cmp_by_name);
      else
        list_bsort (list,sort_cmp_by_ID);
      //timer ();
    }
    
    void example_show_list (LIST *list)
    {
      int i,j,START;
    
      do
      {
        printf ("Show 0=Forward or 1=Reverse ?");
        scanf ("%d",&i);
      }while (i<0 && i>1);
    
      START=i ? LIST_LAST : LIST_FIRST;
      list_seek (list,START, 0, LIST_BY_NUM);
      
      printf ("Showing List:\n");
      
      j=0;
      while (!list_EOL(list))
      { 
        
        show_item (list);
        
        if (++j%3==0)
          printf ("\n");
        
        if (i==0)
          list_seeknext (list);
        else
          list_seekprev (list);
      }
    
      printf ("\n");
    
    }
    
    void example_swap (LIST *list)
    {
      struct itemlist *a,*b;
      int i,j;
      do
      {
        printf ("Witch elementes ?");
        scanf ("%d %d",&i,&j);
      }while (i<0 && j<0);
      
      a=list_seek (list,LIST_FIRST, i, LIST_BY_NUM);
      b=list_seek (list,LIST_FIRST, j, LIST_BY_NUM);
      
      list_swap (list,a,list,b);
    }
    
    void example_free_list (LIST *list)
    {
      struct s1 *ps1;
      
      list_seek (list,LIST_FIRST, 0, LIST_BY_NUM);
      while (!list_EOL(list))
      {
        ps1=list_data(list);
        
        // Freeing my malloc name
        free (ps1->name);
        // Freeing my struct
        free (ps1);
        // Freeing the the current item list
        list_del (list);
      }
    }
    
    void example_search (LIST *list)
    {
      char buff[MAXNAME];
      int ID,i,j;
      
      do
      {
        printf ("Search by 0=Name or 1=ID ?");
        scanf ("%d",&i);
      }while (i<0 || i>1);
      
      j=0;
      if (i==0)
      {
        printf ("Name: ");
        scanf ("%s",buff);
        //timer ();
        list_seek (list,LIST_FIRST, 0, LIST_BY_ITEM,seek_cmp_by_name,buff);
        
        while (!list_EOL(list))
        {
          show_item (list);
          
          if (++j%3==0)
            printf ("\n");
    
          list_seek (list,LIST_CURRENT, 1, LIST_BY_ITEM,seek_cmp_by_name,buff);
        }
      }
      else
      {
        printf ("ID: ");
        scanf ("%d",&ID);
        //timer ();   
        list_seek (list,LIST_FIRST, 0, LIST_BY_ITEM,seek_cmp_by_ID,&ID);
        while (!list_EOL(list))
        {
          show_item (list);
          
          if (++j%3==0)
            printf ("\n");
          
          list_seek (list,LIST_CURRENT, 1, LIST_BY_ITEM,seek_cmp_by_ID,&ID);
        }
        
      }
      printf ("\n%d Item(s) Found\n",j);
      //timer ();
    }
    
    void example ()
    {
      LIST *list;
      int i;
    
      list=list_create ();
      do
      {
        printf ("\nThere are %d item(s) in list\n",list_num_elem(list));
        printf ("(1) Insert\t\t");
        printf ("(2) Load File\t\t");    
        printf ("(3) Insert 500 random item\n");
        printf ("(4) Show List\t\t");    
        printf ("(5) Delete\t\t");
        printf ("(6) Sort\n");
        printf ("(7) Swap\t\t");
        printf ("(8) Free List\t\t");
        printf ("(9) Search\n");
        printf ("(0) Exit\n");
        scanf ("%d",&i);
        
        switch (i)
        {
          case 1:
            example_insert (list);
            break;
    
          case 2:
            example_load_file (list);
            break;
    
          case 3:
            example_insert_many (list);
            break;
    
          case 4:
            example_show_list (list);
            break;
            
          case 5:
            example_delete (list);
            break;
            
          case 6:
            example_sort (list);
            break;
            
          case 7:
            example_swap (list);
            break;
    
          case 8:
            example_free_list (list);
            break;
            
          case 9:
            example_search (list);
            break;
    
            
        }
      }while (i);
      //
      example_free_list (list);
      list_destroy (list);
      //
    }
    
    int main ()
    {
      printf ("\nThis example builds list with this struct:\n");
      printf ("struct s1\n{\n   char *name;\n   int ID;\n}s1;\n\n\n");
    
      example ();
      return 0;
    }
    
    Makefile:
    
    CC        = gcc
    CFLAGS    = -g -Wall
    LFLAGS    =
    SRCPATH   = ./src/
    SOURCES   = $(SRCPATH)list.c $(SRCPATH)example.c
    OBJECTS   =$(SOURCES:.c=.o)
    EXECUTABLE=lista
    
    all:	$(EXECUTABLE)
    
    $(EXECUTABLE):	$(OBJECTS)
    	$(CC) $(LFLAGS) $(OBJECTS) -o $@
    
    .c.o:
    	$(CC) $(CFLAGS) -c $<  -o $@
    
    clean:
    	rm -f $(OBJECTS) $(SRCPATH)*~
    
    tar:
    	tar czvf list.tgz Makefile $(SRCPATH)*.h $(SOURCES)
    
  • Re: Lettura da file con allocazione in una lista

    ixamit ha scritto:


    Il problema che segnali è discusso nel thread seguente di questo sito:
    http://www.iprogrammatori.it/forum-programmazione/cplusplus/problema-con-lista-lineare-t11343.html
    Velocemente il tuo codice potrebbe essere:
    
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct articolo {
      int num;
      struct articolo *next;
    }nodo;
    
    void cons(nodo **head)
    {
      nodo *new;
      int numero;
      
      if ((new=(nodo *)malloc(sizeof(nodo)))==NULL)
      {
        fprintf (stderr,"Cannont allocate\n");
        return ;
      }
      printf("Inserisci numero: "); scanf("%d", &numero);
      new->num=numero;
    
      new->next=*head;
      *head=new;
    }
    
    void cancella (nodo **head)
    {
      nodo *tmp=*head,*next;
      while(tmp)
      {
        next=tmp;
        free (tmp);
        tmp=(next) ? next->next : NULL;
      }
    }
    
    void stampa(nodo **head)
    {
      nodo *tmp=*head;
      while(tmp)
      {
        printf("%d--> ", tmp->num);
        tmp=tmp->next;
      }  
      printf("\n");
    }
    
    int main ()
    {
      nodo *head=NULL;
      
      cons (&head);
      cons (&head);
      cons (&head);
      
      stampa (&head);
      cancella (&head);
      return 0;
    }
    
    Ti segnalo che su piattaforma linux esiste uno strumento di analisi memoria che si chiama 'valgrind' ed un debugger 'ddd'.

    Il mio problema sta nella LETTURA del FILE, il codice che mi hai incollato è solo un codice molto pulito rispetto al mio, ma sempre riguardante la creazione. A me interessa la lettura da file con allocazione in una lista.


    Ti ringrazio comunque.
  • Re: Lettura da file con allocazione in una lista

    Ok ma il tuo inserimento non funziona. Guarda qua':
    
    max@studio:~> valgrind ./a.out                                                   
    ==10503== Memcheck, a memory error detector                                      
    ==10503== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.        
    ==10503== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info      
    ==10503== Command: ./a.out                                                       
    ==10503==                                                                        
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    a                                                                                
    Inserisci numero: 12                                                             
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    a                                                                                
    Inserisci numero: 24                                                             
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    a 13                                                                             
    Inserisci numero: A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                   
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    s                                                                                
    ==10503== Use of uninitialised value of size 8                                   
    ==10503==    at 0x4E6AF4B: _itoa_word (_itoa.c:195)                              
    ==10503==    by 0x4E6CB1A: vfprintf (vfprintf.c:1592)                            
    ==10503==    by 0x4E76009: printf (printf.c:35)                                  
    ==10503==    by 0x400964: stampa (in /home/max/a.out)                            
    ==10503==    by 0x4008F2: main (in /home/max/a.out)                              
    ==10503==                                                                        
    ==10503== Conditional jump or move depends on uninitialised value(s)             
    ==10503==    at 0x4E6AF55: _itoa_word (_itoa.c:195)                              
    ==10503==    by 0x4E6CB1A: vfprintf (vfprintf.c:1592)                            
    ==10503==    by 0x4E76009: printf (printf.c:35)                                  
    ==10503==    by 0x400964: stampa (in /home/max/a.out)                            
    ==10503==    by 0x4008F2: main (in /home/max/a.out)                              
    ==10503==                                                                        
    ==10503== Conditional jump or move depends on uninitialised value(s)             
    ==10503==    at 0x4E6E138: vfprintf (vfprintf.c:1592)                            
    ==10503==    by 0x4E76009: printf (printf.c:35)                                  
    ==10503==    by 0x400964: stampa (in /home/max/a.out)                            
    ==10503==    by 0x4008F2: main (in /home/max/a.out)                              
    ==10503==                                                                        
    ==10503== Conditional jump or move depends on uninitialised value(s)             
    ==10503==    at 0x4E6CC43: vfprintf (vfprintf.c:1592)                            
    ==10503==    by 0x4E76009: printf (printf.c:35)                                  
    ==10503==    by 0x400964: stampa (in /home/max/a.out)                            
    ==10503==    by 0x4008F2: main (in /home/max/a.out)                              
    ==10503==                                                                        
    13--> 24--> 12--> 0-->                                                           
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    q                                                                                
    ==10503==                                                                        
    ==10503== HEAP SUMMARY:                                                          
    ==10503==     in use at exit: 64 bytes in 4 blocks                               
    ==10503==   total heap usage: 4 allocs, 0 frees, 64 bytes allocated              
    ==10503==                                                                        
    ==10503== LEAK SUMMARY:                                                          
    ==10503==    definitely lost: 0 bytes in 0 blocks                                
    ==10503==    indirectly lost: 0 bytes in 0 blocks                                
    ==10503==      possibly lost: 0 bytes in 0 blocks                                
    ==10503==    still reachable: 64 bytes in 4 blocks                               
    ==10503==         suppressed: 0 bytes in 0 blocks                                
    ==10503== Rerun with --leak-check=full to see details of leaked memory           
    ==10503==                                                                        
    ==10503== For counts of detected and suppressed errors, rerun with: -v           
    ==10503== Use --track-origins=yes to see where uninitialised values come from    
    ==10503== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 4 from 4)         
    
  • Re: Lettura da file con allocazione in una lista

    Com'è possibile!
    Da me funziona benissimo!!!!
    Io utilizzo linux UBUNTU 10.10


    Osserva:
    
    daniele@ubuntu:~/Scrivania/File$ make list_num_variabili3
    cc     list_num_variabili3.c   -o list_num_variabili3
    daniele@ubuntu:~/Scrivania/File$ ./list_num_variabili3
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    a
    Inserisci numero: 2
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    a
    Inserisci numero: 5
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    a
    Inserisci numero: 9
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    a
    Inserisci numero: 4
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    a
    Inserisci numero: 7
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    s
    7--> 4--> 9--> 5--> 2--> 0--> 
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    d
    Inserisci il numero che vuoi eliminare:0
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    s
    7--> 4--> 9--> 5--> 2--> 
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    q
    daniele@ubuntu:~/Scrivania/File$
    
  • Re: Lettura da file con allocazione in una lista

    ixamit ha scritto:


    Ok ma il tuo inserimento non funziona. Guarda qua':
    
    max@studio:~> valgrind ./a.out                                                   
    ==10503== Memcheck, a memory error detector                                      
    ==10503== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.        
    ==10503== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info      
    ==10503== Command: ./a.out                                                       
    ==10503==                                                                        
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    a                                                                                
    Inserisci numero: 12                                                             
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    a                                                                                
    Inserisci numero: 24                                                             
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    a 13                                                                         
    Inserisci numero: A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                   
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    s                                                                                
    ==10503== Use of uninitialised value of size 8                                   
    ==10503==    at 0x4E6AF4B: _itoa_word (_itoa.c:195)                              
    ==10503==    by 0x4E6CB1A: vfprintf (vfprintf.c:1592)                            
    ==10503==    by 0x4E76009: printf (printf.c:35)                                  
    ==10503==    by 0x400964: stampa (in /home/max/a.out)                            
    ==10503==    by 0x4008F2: main (in /home/max/a.out)                              
    ==10503==                                                                        
    ==10503== Conditional jump or move depends on uninitialised value(s)             
    ==10503==    at 0x4E6AF55: _itoa_word (_itoa.c:195)                              
    ==10503==    by 0x4E6CB1A: vfprintf (vfprintf.c:1592)                            
    ==10503==    by 0x4E76009: printf (printf.c:35)                                  
    ==10503==    by 0x400964: stampa (in /home/max/a.out)                            
    ==10503==    by 0x4008F2: main (in /home/max/a.out)                              
    ==10503==                                                                        
    ==10503== Conditional jump or move depends on uninitialised value(s)             
    ==10503==    at 0x4E6E138: vfprintf (vfprintf.c:1592)                            
    ==10503==    by 0x4E76009: printf (printf.c:35)                                  
    ==10503==    by 0x400964: stampa (in /home/max/a.out)                            
    ==10503==    by 0x4008F2: main (in /home/max/a.out)                              
    ==10503==                                                                        
    ==10503== Conditional jump or move depends on uninitialised value(s)             
    ==10503==    at 0x4E6CC43: vfprintf (vfprintf.c:1592)                            
    ==10503==    by 0x4E76009: printf (printf.c:35)                                  
    ==10503==    by 0x400964: stampa (in /home/max/a.out)                            
    ==10503==    by 0x4008F2: main (in /home/max/a.out)                              
    ==10503==                                                                        
    13--> 24--> 12--> 0-->                                                           
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                     
    q                                                                                
    ==10503==                                                                        
    ==10503== HEAP SUMMARY:                                                          
    ==10503==     in use at exit: 64 bytes in 4 blocks                               
    ==10503==   total heap usage: 4 allocs, 0 frees, 64 bytes allocated              
    ==10503==                                                                        
    ==10503== LEAK SUMMARY:                                                          
    ==10503==    definitely lost: 0 bytes in 0 blocks                                
    ==10503==    indirectly lost: 0 bytes in 0 blocks                                
    ==10503==      possibly lost: 0 bytes in 0 blocks                                
    ==10503==    still reachable: 64 bytes in 4 blocks                               
    ==10503==         suppressed: 0 bytes in 0 blocks                                
    ==10503== Rerun with --leak-check=full to see details of leaked memory           
    ==10503==                                                                        
    ==10503== For counts of detected and suppressed errors, rerun with: -v           
    ==10503== Use --track-origins=yes to see where uninitialised values come from    
    ==10503== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 4 from 4)         
    

    L'errore che hai commesso è che al posto di scrivere a)dd, poi invio e poi il numero, hai inserito a 13.
    Provalo senza questo errore e poi vedi che funziona.

    PS: L'ho creato senza controlli perchè prima voglio che funzioni e poi inserisco i controlli.
  • Re: Lettura da file con allocazione in una lista

    Non è un errore è corretto inserire + input in linea separati da uno spazio. Se hai dubbi apri un altro topic a riguardo che ti rispondo con eventuali esempi.
    Ecco il tuo programma analizzato da valgrind:
    
    max@studio:~> valgrind ./a.out                                                      
    ==12622== Memcheck, a memory error detector                                         
    ==12622== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.           
    ==12622== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info         
    ==12622== Command: ./a.out                                                          
    ==12622==                                                                           
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                        
    a                                                                                   
    Inserisci numero: 12                                                                
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                        
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                        
    a                                                                                   
    Inserisci numero: 24                                                                
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                        
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                        
    a                                                                                   
    Inserisci numero: 13                                                                
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                        
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit                                        
    s                                                                                   
    ==12622== Use of uninitialised value of size 8                                      
    ==12622==    at 0x4E6AF4B: _itoa_word (_itoa.c:195)                                 
    ==12622==    by 0x4E6CB1A: vfprintf (vfprintf.c:1592)                               
    ==12622==    by 0x4E76009: printf (printf.c:35)                                     
    ==12622==    by 0x400964: stampa (in /home/max/a.out)                               
    ==12622==    by 0x4008F2: main (in /home/max/a.out)                                 
    ==12622==                                                                           
    ==12622== Conditional jump or move depends on uninitialised value(s)                
    ==12622==    at 0x4E6AF55: _itoa_word (_itoa.c:195)                                 
    ==12622==    by 0x4E6CB1A: vfprintf (vfprintf.c:1592)                               
    ==12622==    by 0x4E76009: printf (printf.c:35)                                     
    ==12622==    by 0x400964: stampa (in /home/max/a.out)                               
    ==12622==    by 0x4008F2: main (in /home/max/a.out)                                 
    ==12622==                                                                           
    ==12622== Conditional jump or move depends on uninitialised value(s)                
    ==12622==    at 0x4E6E138: vfprintf (vfprintf.c:1592)                               
    ==12622==    by 0x4E76009: printf (printf.c:35)                                     
    ==12622==    by 0x400964: stampa (in /home/max/a.out)                               
    ==12622==    by 0x4008F2: main (in /home/max/a.out)                                 
    ==12622==                                                                           
    ==12622== Conditional jump or move depends on uninitialised value(s)                
    ==12622==    at 0x4E6CC43: vfprintf (vfprintf.c:1592)
    ==12622==    by 0x4E76009: printf (printf.c:35)
    ==12622==    by 0x400964: stampa (in /home/max/a.out)
    ==12622==    by 0x4008F2: main (in /home/max/a.out)
    ==12622==
    13--> 24--> 12--> 0-->
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    A)dd, D)elete, S)tampa, L)oad, W)rite, Q)uit
    q
    ==12622==
    ==12622== HEAP SUMMARY:
    ==12622==     in use at exit: 64 bytes in 4 blocks
    ==12622==   total heap usage: 4 allocs, 0 frees, 64 bytes allocated
    ==12622==
    ==12622== LEAK SUMMARY:
    ==12622==    definitely lost: 0 bytes in 0 blocks
    ==12622==    indirectly lost: 0 bytes in 0 blocks
    ==12622==      possibly lost: 0 bytes in 0 blocks
    ==12622==    still reachable: 64 bytes in 4 blocks
    ==12622==         suppressed: 0 bytes in 0 blocks
    ==12622== Rerun with --leak-check=full to see details of leaked memory
    ==12622==
    ==12622== For counts of detected and suppressed errors, rerun with: -v
    ==12622== Use --track-origins=yes to see where uninitialised values come from
    ==12622== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 4 from 4)
    max@studio:~>
    
    Ecco il programmino che ti ho postato precedentemente:
    
    max@studio:~> valgrind ./a.out
    ==12676== Memcheck, a memory error detector
    ==12676== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
    ==12676== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
    ==12676== Command: ./a.out
    ==12676==
    Inserisci numero: 12 24 13
    Inserisci numero: Inserisci numero: 13--> 24--> 12-->
    ==12676== Invalid read of size 8
    ==12676==    at 0x4007F3: cancella (in /home/max/a.out)
    ==12676==    by 0x4008A8: main (in /home/max/a.out)
    ==12676==  Address 0x51840e8 is 8 bytes inside a block of size 16 free'd
    ==12676==    at 0x4C23DD8: free (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==12676==    by 0x4007E7: cancella (in /home/max/a.out)
    ==12676==    by 0x4008A8: main (in /home/max/a.out)
    ==12676==
    ==12676==
    ==12676== HEAP SUMMARY:
    ==12676==     in use at exit: 0 bytes in 0 blocks
    ==12676==   total heap usage: 3 allocs, 3 frees, 48 bytes allocated
    ==12676==
    ==12676== All heap blocks were freed -- no leaks are possible
    ==12676==
    ==12676== For counts of detected and suppressed errors, rerun with: -v
    ==12676== ERROR SUMMARY: 3 errors from 1 contexts (suppressed: 4 from 4)
    max@studio:~>
    
    Ecco un errore nella funzione cancella. Mi dice che assegna un indirizzo non valido... in effetti non posso assegnare tmp dopo una cancellazione... per cui:
    
    void cancella (nodo **head)
    {
      nodo *tmp=*head,*next;
      while(tmp)
      {
        next=tmp->next;
        free (tmp);
        tmp=next;
      }
    }
    
    compilo ed eseguo sotto valgrind:
    
    max@studio:~> gcc -Wall lista.c
    max@studio:~> valgrind ./a.out
    ==12699== Memcheck, a memory error detector
    ==12699== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
    ==12699== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
    ==12699== Command: ./a.out
    ==12699==
    Inserisci numero: 12 24 13
    Inserisci numero: Inserisci numero: 13--> 24--> 12-->
    ==12699==
    ==12699== HEAP SUMMARY:
    ==12699==     in use at exit: 0 bytes in 0 blocks
    ==12699==   total heap usage: 3 allocs, 3 frees, 48 bytes allocated
    ==12699==
    ==12699== All heap blocks were freed -- no leaks are possible
    ==12699==
    ==12699== For counts of detected and suppressed errors, rerun with: -v
    ==12699== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
    max@studio:~>
    
    Nessun errore, tre blocchi allocati e tre liberati
  • Re: Lettura da file con allocazione in una lista

    Capisco. MA tu utilizzi MAC vero???

    Comunque, ritornando al discorso della lettura da file???? Come posso fare??

    Grazie
  • Re: Lettura da file con allocazione in una lista

    Ho capito che non capisci ma non sei neanche attento:
    
    --- cut ---
    ==12676==  Address 0x51840e8 is 8 bytes inside a block of size 16 free'd
    ==12676==    at 0x4C23DD8: free (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==12676==    by 0x4007E7: cancella (in /home/max/a.out)
    ==12676==    by 0x4008A8: main (in /home/max/a.out)
    --- cut ---
    
    Qui nella 2^ riga mi dice linux amd64
  • Re: Lettura da file con allocazione in una lista

    http://www.cplusplus.com/reference/clibrary/cstdio/fscanf/
  • Re: Lettura da file con allocazione in una lista

    Ahahha che sciocco, scusami non ci ho fatto caso che utilizzi anche tu linux.
    Comunque il mio problema di leggere i dati da un file e metterli dentro una lista rimane sempre. Non riesco a trovare una guida perfetta o qualcuno che me lo spiega.
    Questo link che mi hai incollato non è tanto comprensivo, ne ho visitati tanti di link ma nessuno spiega bene quello che cerco io.
Devi accedere o registrarti per scrivere nel forum
36 risposte