我一直在使用指针和malloc,我不知道如何正确使用free()。我有一个程序,允许用户在选择特定选项时添加数据记录。我的程序只允许此功能发生一次,然后我得到一个段错误。我不认为我正在使用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
下面是我没有包含的菜单循环。我的问题在于我的添加功能,我在这里使用free():
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
答案 0 :(得分:0)
last
指向first
,在addRecord()
的第一次通话结束时被释放。在第二次调用时,您将崩溃,因为last
不再指向已分配的内存。但是,更有问题的是您没有为新记录分配任何新内存。请参阅realloc()
。