Search code examples
cmallocfreerealloc

Malloc Realloc Free


Hello I for an exercise at University i need to malloc an array with this way. The array at stars has 1 slot. If the inputs are more than one then the array is doubled. If the inputs are more than 2 then it is doubled again etc. After this I have to crop the array to fit to the number of inputs. For example if I have 5 inputs then the array will have 8 slots and I must make it to have 5 slots which I cannot figure out how. Here is my code so far:

nameInfoT* ReadNames(int* size){
    nameInfoT* names ;
    int array_size=1;
    int entries=0;
    char input[length];
    names=(nameInfoT*) malloc(sizeof(nameInfoT)*array_size);

    do{
        scanf("%s",input);
        if(!strcmp(input,"END")) break;

        if(entries==array_size){
            array_size=array_size*2;
            names= (nameInfoT*) realloc(names,sizeof(nameInfoT)*array_size);
        }

        names[entries].name=(char*)malloc(sizeof(char)*strlen(input));
        strcpy(names[entries].name,input);

        entries++;

    }while(1);

    printf("there are %d free spaces \n",array_size-entries);
    *size=entries;
    printf("there are %d entries \n",*size);

    int i;
    for(i=array_size;i>entries;i--){
        free(names[i]);//here it won't compile 
    }
    return names;

}

Solution

  • You can only free the result of malloc/calloc/realloc. You cannot free individual elements. So in the end you can simply realloc again to the desired final size.