I have been using pointers and malloc and I do not know how to use free() properly. I have a program that allows the user to add a record of data when they select a specific option. My program allows this function to happen only once and then I get a segfault. I do not think I am using free() properly and was hoping someone could point out my problem. I have the global variables:
int records = 5;
int access = 0; //initialize access counter to 0
int count = 0;
struct childrensBook *first; //initialize first pointer
struct childrensBook *last; //initialize last pointer
struct childrensBook *temp; //initialize temp pointer
I then have the start of my main function where I include predefined records:
int main(void)
{
last = (struct childrensBook *) malloc(records * sizeof(struct childrensBook)); //allocate memory to "last" pointer
first = last;
memcpy(last->title, "We're Going on a Bear Hunt", 27); //Beginning of all 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 to record count
memcpy(last->title, "One Fish\n Two 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 to record count
memcpy(last->title, "Snowmen At Night", 17);
memcpy(last->author, "Caralyn Buehner", 16);
last->price = 16.99;
last++; //incrememnts pointer
count = count + 1; //adds 1 to record count
memcpy(last->title, "Harold and the Purple Crayon", 29);
memcpy(last->author, "Crockett Johnson", 17);
last->price = 6.99
Below this is just my menu loop which I have not included. My problem lies in my add function where I am using free() which is here:
addRecord() //Add Function
{
last=first; //get pointer in correct position
memcpy(&temp, &last, records *sizeof(struct childrensBook)); //use memcpy to copy info from last to temp
fprintf(stderr, "\nYou have added the record:\n==========================\nBook: %s\nWritten by: %s\nPrice: $%.2f\n", temp->title, temp->author,
temp->price);
temp++;
free(last); //problem?? I have tried using free(first), free(last) and free(temp) and none work....
count = count + 1;
}//end addRecord
I also have done it this way and it still does 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 to copy info from last to temp
fprintf(stderr, "\nYou have added the record:\n==========================\nBook: %s\nWritten by: %s\nPrice: $%.2f\n", temp->title, temp->author,
temp->price);
temp++;
free(last);
count = count + 1;
}//end addRecord