2015-11-17 23 views
0

我試圖創建一個ADT, 首先,這裏是關於它的基本信息:C-的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。 我在哪裏出錯了?

+1

您還沒有分配'foodCompanies'任何地方,但試圖索引並將其分配。在C中爲 –

+0

,'malloc()'和函數系列的返回值爲'void *'類型,可以將其分配給任何其他指針。鑄造返回類型是完全不必要的,並且在調試和維護代碼時會導致困難。 typedef名稱「Orange」具有誤導性,因爲它實際上是一種指針類型。對於typedef來說,更好的方法就是不帶指針的'struct orange_t',然後根據需要在代碼體中添加'*'。 – user3629249

+0

枚舉以0開頭(除非另有特別定義),所以'expirationMonth'的檢查是不正確的,除非枚舉被修改,所以第一個條目是:'JAN = 1,' – user3629249

回答

1

JAN爲0.如果expirationMonth<1您從orangeCreate返回NULL

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

1

的問題是,你是不是對char** foodCompanies;


分配內存在內存分配這裏

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

您已經分配空間的指針變量char** foodCompanies;,但還沒有分配空間的地方會指向。

1

在訪問它之前,您必須分配一些內存並將其地址存儲到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; 
} 

注:這是鼓勵投的malloc()的結果C.
c - Do I cast the result of malloc? - Stack Overflow