簡體   English   中英

C-持續崩潰的ADT

[英]C- an ADT that keeps crashing

我正在嘗試創建ADT,首先,這是有關它的基本信息:

typedef struct orange_t* Orange;

typedef enum {
JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC,
} Month;

struct orange_t {

short size;
Month expirationMonth;
char** foodCompanies;
int maxNumberOfFoodCompanies;
int sellingPrice;
};

現在,我正在嘗試創建一個將“創建”新橙色的函數,如下所示:

Orange orangeCreate(short size,Month expirationMonth
    ,int maxNumberOfFoodCompanies,int sellingPrice)
 {
   Orange new_orange=(Orange)malloc(sizeof(struct orange_t));
   if(new_orange==NULL)
   {
        return NULL;
    }
   if((sellingPrice<0)||(size>256||size<1)||(maxNumberOfFoodCompanies<0)||(expirationMonth>12)
        ||(expirationMonth<1))
        {
        return NULL;
        }
new_orange->sellingPrice=sellingPrice;
new_orange->maxNumberOfFoodCompanies=maxNumberOfFoodCompanies;
new_orange->expirationMonth=expirationMonth;
new_orange->size=size;
for(int i=0;i<new_orange->maxNumberOfFoodCompanies;i++)
{
    new_orange->foodCompanies[i]=NULL;
}
return new_orange;
}

當我嘗試使用簡單的main()檢查功能時:

int main()
{
Orange orange=orangeCreate(3,JAN,10,4);
printf("the size is %d\n",orange->size);
orangeDestroy(orange);
return 0;
}

程序不斷崩潰,我想我沒有按應有的方式更改橙色值,它們可能仍然是NULL 我在哪里錯了?

JAN為0。如果expirationMonth<1 ,則從orangeCreate返回NULL

另外:您沒有檢查orangeCreate的返回值。 當您僅返回NULL而不free分配的new_orange時,就會在orangeCreate中泄漏內存。

問題在於您沒有為char** foodCompanies;分配內存char** foodCompanies;


在這里分配內存

Orange new_orange=malloc(sizeof(struct orange_t));

您已經為指針變量char** foodCompanies;分配了空間char** foodCompanies; ,但尚未分配指向的空間。

您必須分配一些內存並將其地址存儲在new_orange->foodCompanies然后再訪問它。

可能的解決方法:

Orange orangeCreate(short size,Month expirationMonth
    ,int maxNumberOfFoodCompanies,int sellingPrice)
 {
   Orange new_orange=malloc(sizeof(struct orange_t));
   if(new_orange==NULL)
   {
        return NULL;
    }
   if((sellingPrice<0)||(size>256||size<1)||(maxNumberOfFoodCompanies<0)||(expirationMonth>12)
        ||(expirationMonth<1))
        {
        return NULL;
        }
new_orange->sellingPrice=sellingPrice;
new_orange->maxNumberOfFoodCompanies=maxNumberOfFoodCompanies;
new_orange->expirationMonth=expirationMonth;
new_orange->size=size;
new_orange->foodCompanies=malloc(sizeof(char*)*new_orange->maxNumberOfFoodCompanies); /* add this line */
for(int i=0;i<new_orange->maxNumberOfFoodCompanies;i++)
{
    new_orange->foodCompanies[i]=NULL;
}
return new_orange;
}

注意:不建議在C中malloc()的結果。
c-我是否強制轉換malloc的結果? - 堆棧溢出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM