I'm writing a simple function to create a list which represents a deck of cards. Here's the definition of the structs
typedef struct {
float valoreEff;
char *seme;
char *valore;
} carta;
struct Mazzo {
carta info;
struct Mazzo *nextPtr;
};
typedef struct Mazzo mazzo;
typedef mazzo *mazzoPtr;
Here's the function which returns a pointer to the first element of the list
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->n开发者_JS百科extPtr=sMazzoPtr;
sMazzoPtr=newPtr;
}
}
return sMazzoPtr;
}
GCC gives me no compile-time errors, but when I execute the program, this is the output
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
I've also tried Valgrind, but I can't figure out the mistake in the code.
==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==
I hope you can help me :)
The problem appears to be at the line where you call malloc()
.
newPtr
is of type mazzo*
, but you are allocating space for a carta
, which is too small.
I think it should be newPtr=malloc(sizeof(mazzo));
While this may not be an option for you, you would be better off using C++. Among its many software engineering benefits, its new
idiom for allocating memory prevents exactly this kind of error, since you must explicitly use the object type: newPtr = new mazzo;
精彩评论