[英]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.