c - How do I use free() properly to free memory when using malloc? -
i have been using pointers , malloc , not know how use free() properly. have program allows user add record of data when select specific option. program allows function happen once , segfault. not think using free() , hoping point out problem. have global variables:
int records = 5; int access = 0; //initialize access counter 0 int count = 0; struct childrensbook *first; //initialize first pointer struct childrensbook *last; //initialize last pointer struct childrensbook *temp; //initialize temp pointer
i have start of main function include predefined records:
int main(void) { last = (struct childrensbook *) malloc(records * sizeof(struct childrensbook)); //allocate memory "last" pointer first = last; memcpy(last->title, "we're going on bear hunt", 27); //beginning of predefined records memcpy(last->author, "michael rosen", 14); last->price = 7.99; last++; //incrememnts pointer count = count + 1; //begins counting of records memcpy(last->title, "goodnight moon", 15); memcpy(last->author, "margaret wise brown", 20); last->price = 8.99; last++; //incrememnts pointer count = count + 1; //adds 1 record count memcpy(last->title, "one fish\n 2 fish\nred fish\n blue fish", 38); memcpy(last->author, "dr. seuss", 10); last->price = 8.99; last++; //incrememnts pointer count = count + 1; //adds 1 record count memcpy(last->title, "snowmen @ night", 17); memcpy(last->author, "caralyn buehner", 16); last->price = 16.99; last++; //incrememnts pointer count = count + 1; //adds 1 record count memcpy(last->title, "harold , purple crayon", 29); memcpy(last->author, "crockett johnson", 17); last->price = 6.99
below menu loop have not included. problem lies in add function using free() here:
addrecord() //add function { last=first; //get pointer in correct position memcpy(&temp, &last, records *sizeof(struct childrensbook)); //use memcpy copy info last temp fprintf(stderr, "\nyou have added record:\n==========================\nbook: %s\nwritten by: %s\nprice: $%.2f\n", temp->title, temp->author, temp->price); temp++; free(last); //problem?? have tried using free(first), free(last) , free(temp) , none work.... count = count + 1; }//end addrecord
i have done way , still not work:
addrecord() //add function { last=first; //get pointer in correct position temp = (struct childrensbook *) malloc(records * sizeof(struct childrensbook)); memcpy(&temp, &last, records *sizeof(struct childrensbook)); //use memcpy copy info last temp fprintf(stderr, "\nyou have added record:\n==========================\nbook: %s\nwritten by: %s\nprice: $%.2f\n", temp->title, temp->author, temp->price); temp++; free(last); count = count + 1; }//end addrecord
last
points first
gets freed @ end of first call addrecord()
. on second call crash since last
no longer points allocated memory. but, more problematic not allocating new memory new record. see realloc()
.
Comments
Post a Comment