提供以下struct
struct HotelManagement
{
Hotel_t *hotel;
Customer_t *customers;
reservation_t *reservations;
int physicalSize;
int registerdSize;
int physicalSizeReserv;
int registerdSizeReserv;
} typedef HotelManagement_t;
以下main
:
printf("-----DETAILS FOR CUSTOMER-----\n");
printf("enter name ");
gets(tempName);//"cleans" the buffer
gets(tempName);
customerName = strdup(tempName);
printf("nenter credit card ");
gets(tempCredit);
creditCardNumber = strdup(tempCredit);
printf("enter credit card expiration month(mm)\n");
printf("enter credit card expiration year(yyyy)\n");
scanf("%d",&month);
scanf("%d",&year);
addCustomer(customerName,creditCardNumber, month,year,&hm);
以及addCustomer
的以下实现:
void addCustomer(char *customerName, char *numberOfCreditCard,int month,int year,HotelManagement_t *hotelMang)
{
int *m = &month;
int *y = &year;
int i;
if (hotelMang->physicalSize == hotelMang->registerdSize)
{
hotelMang->customers = (Customer_t*)realloc(hotelMang->customers, hotelMang->registerdSize * sizeof(Customer_t));
}
hotelMang->customers[hotelMang->registerdSize].id = hotelMang->registerdSize+1;//id starts with '1'
hotelMang->customers[hotelMang->registerdSize].cName = (char*)malloc(strlen(customerName)*sizeof(char));//initalize space for the Customers name
strcpy(hotelMang->customers[hotelMang->registerdSize].cName ,customerName);
if (checkValidCreditCard(&month,&year,numberOfCreditCard) == 1)
{
hotelMang->customers[hotelMang->registerdSize].credit = (char*)malloc(strlen(numberOfCreditCard)*sizeof(char));//initalize size
strcpy(hotelMang->customers[hotelMang->registerdSize].credit, numberOfCreditCard);
hotelMang->customers[hotelMang->registerdSize].month = month;
hotelMang->customers[hotelMang->registerdSize].year = year;
}
//increments
for (i = 0; i <= hotelMang->registerdSize; i++)
{
printOneCustomer(hotelMang->customers[i]);
}
hotelMang->registerdSize= hotelMang->registerdSize +1;
}
这是一个初始化数组的函数......
hotelManagement->customers = (Customer_t*)calloc(1, sizeof(Customer_t));
hotelManagement->hotel->roomsMat = (Room_t**)calloc(floors, sizeof(Room_t*));
hotelManagement->reservations = (reservation_t*)calloc(1, sizeof(reservation_t));
我想为客户重新分配空间,因为我向数组中添加了越来越多的客户,但它引发了异常。可能是什么原因?
答案 0 :(得分:0)
第一次致电addCustomer
时,hotelManagement->registerdSize
的值为 零 。当您调用大小为零的realloc
时,会发生什么?实现已定义。 realloc
函数可以返回原始指针。 可以返回 null 指针。它甚至可以释放内存。
考虑到您将hotelMang->customers
初始化为指向&#34;数组&#34;对于一个 Customer_t
结构,您应该将hotelManagement->registerdSize
初始化为1
。然后在重新分配时使用(hotelManagement->registerdSize + 1)
。
此外,您永远不会检查错误,请记住calloc
和realloc
都可能返回空指针。对realloc
的调用意味着你将失去内存泄漏,因为你丢失了原始指针。始终使用临时变量来获得realloc
的结果。