Search code examples
cfreedynamic-memory-allocation

free function causing a SIGTRAP


I've a newbie question regarding freeing memory allocated for an array of struct. This is the code:

typedef struct {
    char code[6];
    char name[31];
    char cname[31];
    int anno;

} cliente;

cliente *readcostumers(char*filename,int * dim) {
    int i;
    cliente *d;
    cliente temp;
    FILE*fp;
    fp=fopen(filename,"r");
    *dim=0;
    //count the number of lines 
    while(fscanf(fp,"%s %s %s %d", temp.code, temp.name, temp.cname,&(temp.anno))==4)
        (*dim)++;
    rewind(fp);
    //allocate "dim" struct
    int ss = sizeof(cliente);
    d = (cliente*)malloc(ss * (*dim));
    cliente *currCli = d;
    //assign lines to struct
    for(i=0; i<*dim; i++) {
        fscanf(fp,"%s %s %s %d",currCli->code, currCli->name, currCli->cname, &(currCli->anno));
        currCli = currCli + ss;
    }
    fclose(fp);
    return d;
}

This piece of code basically reads a text file, with any number of lines, formatted with a specific pattern and assign the contents to an array of strcut cliente.

This seems to work fine, except when i free the memory previous allocated:

int main () {
    int x,i;


    cliente *f = readcostumers("c:/temp/clienti.txt",&x);
    int len = sizeof(cliente);
    for(i=0; i<x; i++) {        
        printf("\n%s %s %s %d",(f + len*i)->code, (f + len*i)->name, 
               (f + len*i)->cname, (f + len*i)->anno);      
    }
    free(f);
}

The last statement free(f) causes a SIGTRAP exception, altough the values printed are correct read from file.

The file content is this:

A3789 Paolo Rossi 2001
X478D Marcantonio Bianchi 2004

Where is the mistake?


Solution

  • When you increment currCli in readcostumers you should use 1 and in main you shouldn't multiply the index with len. These are taken care of by the language. These two errors are compensating each other, but in the mean time you are accessing outside the allocated memory and most likely overwriting internal administration of the heap allocation algorithms. Ultimately resulting in a crash in free.

    Look into the valgrind tool as it finds these kind of errors flawlessly.