Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 12
  1. #1
    Utente bannato
    Registrato dal
    Oct 2010
    Messaggi
    1,219

    [C]Usare la free su array di strutture

    Salve,se io alloco n strutture dinamicamente,e una strutture è composta così:
    codice:
    typedef struct
    {
        char *nome;
        char *cognome;
        int eta;
    }lista;
    E creo una lista chiamata stack che alloco dinamicamente:
    codice:
    lista *stack;
    E i campi nome e cognome li acquisisco allocando dinamicamente la memoria.
    Mi rimane sempre questo dubbio fondamentale:
    Alla fine devo liberare solo la lista in questo modo:
    codice:
    for(i=0;i<n;i++)
        free(stack[i]);
    Oppure devo liberare anche gli elementi nome e cognome,che ho allocato dinamicamente?
    Mi rimane sempre il dubbio,alla fine usando la free sulla struttura libero la struttura,ma cosa a proposito della memoria allocato all' interno dei suoi puntatori?Chiaritemi questo dubbio

  2. #2
    Devi mettere il codice dell'allocazione...
    Fracty - The Fractal Generator



    If you cannot choose a concise name that expresses what the method does, it is possible that your method is attempting to perform too many diverse tasks.

  3. #3
    Utente bannato
    Registrato dal
    Oct 2010
    Messaggi
    1,219
    codice:
    int main(int agrc,char **agrv)
    {
        char *buffer;
        lista *stack1,*stack2;
        int *num1,*num2,i;
        bool continue;
        num1=(int*)malloc(sizeof(int));
        num2=(int*)malloc(sizeof(int));
        (*num1)=0;
        (*num2)=0;
        if(num==NULL)
            MERROR
        printf("Inserire la prima lista di strutture:\n");
        do
        {
            insert(stack1,num1);
            printf("Continuare ad inserire elementi?-->");
            buffer=input();
            continue=(atoi(buffer));
            free(buffer);
        }while(continue);
    codice:
    char *input (void)
    {
        char *buffer;
        char seeker;
        int size=1;
        buffer=(char*)malloc(sizeof(char));
        if(buffer==NULL)
            MERROR
        while((seeker=getchar())!=10)
        {
            buffer[size-1]=seeker;
            buffer=(char*)realloc(buffer,sizeof(char*));
            if(buffer==NULL)
                MERROR
        }
        buffer[size-1]='\0';
        return buffer;
    }
    
    bool insert(lista *ptr,int *num)
    {
        (*num)++;
        char *buffer;
        if((*num)==1)
        {
            ptr=(lista*)malloc(sizeof(lista));
            if(ptr==NULL)
                MERROR
        }
        else
        {
            ptr=(lista*)realloc(ptr,(*num)*sizeof(lista));
            if(ptr==NULL)
                MERROR
        }
        printf("Inserisci nome:-->");
        ptr[*num-1].nome=input();
        printf("Inserisci cognome:-->");
        ptr[*num-1].cognome=input();
        printf("Inserisci eta:-->");
        buffer=input();
        ptr[*num-1]=atoi(buffer);
        free(buffer);
        return true;
    }
    E' un pò strutturata la cosa,comunque sono queste le funzioni,uso la realloc come vedi.

  4. #4
    In linea di massima:

    codice:
    for( i = 0; i != n; ++i )
    {
    	free(nome);
    	free(cognome);
    }
    
    free(lista);

    Ma vedi che ci sarebbero diverse cose da rivedere, secondo me l'hai strutturata un po' male come cosa.
    Fracty - The Fractal Generator



    If you cannot choose a concise name that expresses what the method does, it is possible that your method is attempting to perform too many diverse tasks.

  5. #5
    Utente bannato
    Registrato dal
    Oct 2010
    Messaggi
    1,219
    Aspetta,ti faccio anche vedere qual'è esattamente il mio dubbio,se fare così:
    codice:
    for(i=0;i<(*num2);i++)
        {
            free(stack2[i].nome);
            free(stack2[i].cognome);
            free(stack2[i]);
        }
    Oppure così:
    codice:
    for(i=0;i<(*num2);i++)
      {
          free(stack2[i]);
      }
    In pratica il mio dubbio è sapere se devo anche liberare la memoria allocata sui puntatori all' interno della struttura.
    Comunque così mi ci trovo bene,una volta che ho *num2 (che equivale a n,è il numero di strutture) posso fare qualsiasi cosa,anche un bubblesort della struttura in base all' età.

  6. #6
    codice:
    for(i=0;i<(*num2);i++)
        {
            free(stack2[i].nome);
            free(stack2[i].cognome);
           
        }
    
     free(stack2);
    Fracty - The Fractal Generator



    If you cannot choose a concise name that expresses what the method does, it is possible that your method is attempting to perform too many diverse tasks.

  7. #7
    Utente bannato
    Registrato dal
    Oct 2010
    Messaggi
    1,219
    Ah già ! Mi ero dimenticato che la lista è un semplicissimo array.
    Un altro dubbio:come vedi ho usato una variabile che si chiama continue,ma continue è una parola chiave del C.
    Sto provando a usare:
    codice:
    #undef continue
    Ma niente da fare,me la conta come parola chiave.Pur sapendo che andrei fuori gli standard del c,vorrei sapere come indefinire (se esiste il termine) questa parola chiave per poi usarla come il nome di una variabile.

  8. #8
    Non credo proprio che si possa fare perchè continue fa parte del cuore del linguaggio. Ma in ogni caso anche se si potesse eviterei assolutamente di utilizzarla con un altro significato.
    Fracty - The Fractal Generator



    If you cannot choose a concise name that expresses what the method does, it is possible that your method is attempting to perform too many diverse tasks.

  9. #9
    Utente bannato
    Registrato dal
    Oct 2010
    Messaggi
    1,219
    Comunque continua a darmi SIGSEV (segmentation fault) quando chiamo la free,riposto il codice completo corretto:
    codice:
    int main(int agrc,char **agrv)
    {
        char *buffer;
        lista *stack1,*stack2;
        int *num1,*num2,i;
        bool continua;
        num1=(int*)malloc(sizeof(int));
        num2=(int*)malloc(sizeof(int));
        (*num1)=0;
        (*num2)=0;
        if(num1==NULL||num2==NULL)
            MERROR
        printf("Inserire la prima lista di strutture:\n");
        do
        {
            insert(stack1,num1);
            printf("Continuare ad inserire elementi?-->");
            buffer=input();
            continua=(atoi(buffer));
            free(buffer);
        }while(continua);
        printf("Inserire la seconda lista di strutture:\n");
        do
        {
            insert(stack2,num2);
            printf("Continuare ad inserire elementi?-->");
            buffer=input();
            continua=(atoi(buffer));
            free(buffer);
        }while(continua);
        printf("%d,%d\n",*num1,*num2);      /* debug */
        for(i=0;i<(*num1);i++)
        {
            free(stack1[i].nome);
            free(stack1[i].cognome);
        }
        for(i=0;i<(*num2);i++)
        {
            free(stack2[i].nome);
            free(stack2[i].cognome);
        }
        free(stack1);
        free(stack2);
        free(num1);
        free(num2);
        return 1;
    }
    codice:
    char *input (void)
    {
        char *buffer;
        char seeker;
        int size=1;
        buffer=(char*)malloc(sizeof(char));
        if(buffer==NULL)
            MERROR
        while((seeker=getchar())!=10)
        {
            buffer[size-1]=seeker;
            buffer=(char*)realloc(buffer,sizeof(char*));
            if(buffer==NULL)
                MERROR
        }
        buffer[size-1]='\0';
        return buffer;
    }
    
    bool insert(lista *ptr,int *num)
    {
        (*num)++;
        char *buffer;
        if((*num)==1)
        {
            ptr=(lista*)malloc(sizeof(lista));
            if(ptr==NULL)
                MERROR
        }
        else
        {
            ptr=(lista*)realloc(ptr,(*num)*sizeof(lista));
            if(ptr==NULL)
                MERROR
        }
        printf("Inserisci nome:-->");
        ptr[*num-1].nome=input();
        printf("Inserisci cognome:-->");
        ptr[*num-1].cognome=input();
        printf("Inserisci eta:-->");
        buffer=input();
        ptr[*num-1].eta=atoi(buffer);
        free(buffer);
        return true;
    }
    Crasha esattamente alla riga 78:
    codice:
    free(stack1[i].nome);
    Eppure se ho fatto tutto bene stack1 dovrebbe avere spazio in memoria,nella funzione di inserimento uso la malloc e se ritorna il puntatore a vuoto ho anche previsto un errore,non capisco perchè fa così.

  10. #10
    Fai il debug, vedi quanto valgono i e stack1[i].nome prima di rilasciare memoria in modo da vedere se hai toccato parti di memoria che non dovevi toccare.
    Fracty - The Fractal Generator



    If you cannot choose a concise name that expresses what the method does, it is possible that your method is attempting to perform too many diverse tasks.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.