c - Function with realloc crashes program after second run -
it seems after second time in function realocvet runs, error message "malloc: *** error object 0x7f8bfac039b0: pointer being realloc'd not allocated" appears.
void realocvet (float *precolist, char *nomelist, short int *quantidadelist) { static short int p=2,n=100,q=2; p=4*p; n=4*n; q=4*q; precolist =realloc(precolist,p * sizeof(float)); nomelist =realloc(nomelist,n * sizeof(char)); quantidadelist =realloc(quantidadelist,q * sizeof(short int )); } void insertdata (float *precolist, char *nomelist, short int *quantidadelist, struct newcard mycard) { static short int slotsavailable = 2, aux=2,currentcard=0,nnchar=0; short int nchar; precolist[currentcard] = mycard.preco; quantidadelist[currentcard] = mycard.quantidade; (nchar=0;nchar<50;nchar++) { nomelist[nnchar] = mycard.nome[nchar]; nnchar++; } currentcard++; slotsavailable--; if (slotsavailable==0) { realocvet(precolist, nomelist, quantidadelist); slotsavailable = aux; aux = 2*aux; } }
you pass in pointer, float *precolist, realloc (potentially change). problem when return, caller still has old value of pointer.
when call function again, called old value points free'd memory.
void realocvet (float **precolist, char **nomelist, short int **quantidadelist) { static short int p=2,n=100,q=2; p=4*p; n=4*n; q=4*q; *precolist =realloc(*precolist,p * sizeof(float)); *nomelist =realloc(*nomelist,n * sizeof(char)); *quantidadelist =realloc(*quantidadelist,q * sizeof(short int )); }
Comments
Post a Comment