2011-01-06 50 views
2

我在寫一個簡單的函數來創建一個代表一副牌的列表。 這裏的結構內存動態分配的問題:main:malloc.c:3096:sYSMALLOc

typedef struct { 
float valoreEff; 
char *seme; 
char *valore; 
} carta; 

struct Mazzo { 
carta info; 
struct Mazzo *nextPtr; 
}; 


typedef struct Mazzo mazzo; 
typedef mazzo *mazzoPtr; 

的定義,下面是它返回一個指向列表的第一個元素

mazzoPtr caricaMazzo(void){ 

mazzoPtr sMazzoPtr=NULL; 
int val,seme; 
carta buffer; 
mazzoPtr newPtr; 
    char *tabValori[10]={"Asso","Due","Tre","Quattro","Cinque","Sei","Sette","Donna","Cavallo","Re"}; 
    char *tabSeme[4]={"Denari","Spade","Coppe","Bastoni"}; 

for(seme=0;seme<4;seme++){ 
    for(val=0;val<10;val++){ 
    buffer.seme=tabSeme[seme]; 
    buffer.valore=tabValori[val]; 
    if (val<=7) { 
    buffer.valoreEff=val+1; 
    } 
    else { 
    buffer.valoreEff=0.5; 
    } 
    printf("ok\n"); 
    newPtr=malloc(sizeof(carta)); 
    if (newPtr==NULL){ 
    printf("Memoria insufficiente\n"); 
    return NULL; 
    } 
    newPtr->info=buffer; 
    newPtr->nextPtr=sMazzoPtr; 
    sMazzoPtr=newPtr; 
    } 
} 
return sMazzoPtr; 
} 

GCC沒有給我編譯時錯誤的功能,但是當我執行程序,這是輸出

ok 
ok 
main: malloc.c:3096: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) 
&((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) 
&& old_size == 0) || ((unsigned long) (old_size) >= (unsigned long) 
((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * 
(sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size 
& 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed. 
Aborted 

我也試過Valgrind,但我無法弄清代碼中的錯誤。

==21848== Invalid write of size 4 
==21848== at 0x8048554: caricaMazzo (in /home/gianluca/Dropbox/PROGRAMMI/progetto/main) 
==21848== by 0x8048431: main (in /home/gianluca/Dropbox/PROGRAMMI/progetto/main) 
==21848== Address 0x419e034 is 0 bytes after a block of size 12 alloc'd 
==21848== at 0x4025BD3: malloc (vg_replace_malloc.c:236) 
==21848== by 0x804851D: caricaMazzo (in /home/gianluca/Dropbox/PROGRAMMI/progetto/main) 
==21848== by 0x8048431: main (in /home/gianluca/Dropbox/PROGRAMMI/progetto/main) 
==21848== 

我希望你能幫助我:)

回答

5

的問題似乎是在您致電malloc()行。

newPtr的類型是mazzo*,但是您爲carta分配空間太小。

我覺得應該是newPtr=malloc(sizeof(mazzo));

+4

另外 - 您可以通過使用習慣用法來防止此類錯誤`newPtr = malloc(sizeof(* newPtr));` - 不管指針的類型如何,都無法幫助但是正確。稍後有人閱讀代碼不需要在源代碼中跳轉,以確保指定的指針的「sizeof」操作數的類型正確。 – 2011-01-06 18:25:17

0

雖然這可能不是一個選擇,你會用C會更好++。在其衆多軟件工程優勢中,其new成語的分配內存可以防止出現這種錯誤,因爲您必須明確地使用對象類型:newPtr = new mazzo;