0
我一直在使用指針和malloc,我不知道如何正確使用free()。我有一個程序,允許用戶在選擇特定選項時添加數據記錄。我的程序允許這個功能只發生一次,然後我得到一個段錯誤。我不認爲我正在使用免費(),並希望有人能指出我的問題。我有全局變量:如何在使用malloc時正確使用free()來釋放內存?
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
然後我有,我有預定記錄我的主要功能的開始:
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
下面這只是我的菜單循環,我還沒有包括在內。我的問題在於我的附加功能,其中我使用免費的(),它是在這裏:
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
我也這樣做了,它仍然不工作:
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
請不要強制'malloc()'。這不是一個好主意,有幾個原因:http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc。 – cyphar
好像你打了幾次免費電話(我認爲是2),當你試圖釋放釋放的對象時,你有崩潰,更不用說你沒有分配臨時工。 – ColdSteel
'memcpy(&temp,&last,records * sizeof(struct childrensBook));':'temp'不分配。也'''? – BLUEPIXY