尝试在函数

时间:2017-12-30 13:29:52

标签: c pointers realloc

提供以下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));

我想为客户重新分配空间,因为我向数组中添加了越来越多的客户,但它引发了异常。可能是什么原因?

1 个答案:

答案 0 :(得分:0)

第一次致电addCustomer时,hotelManagement->registerdSize的值为 。当您调用大小为零的realloc时,会发生什么?实现已定义realloc函数可以返回原始指针。 可以返回 null 指针。它甚至可以释放内存。

考虑到您将hotelMang->customers初始化为指向&#34;数组&#34;对于一个 Customer_t结构,您应该将hotelManagement->registerdSize初始化为1。然后在重新分配时使用(hotelManagement->registerdSize + 1)

此外,您永远不会检查错误,请记住callocrealloc都可能返回空指针。对realloc的调用意味着你将失去内存泄漏,因为你丢失了原始指针。始终使用临时变量来获得realloc的结果。