内存动态分配问题:main:malloc.c:3096:sYSMALLOc

时间:2011-01-06 13:55:52

标签: c list memory malloc valgrind

我正在编写一个简单的函数来创建一个代表一副牌的列表。 这是结构的定义

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== 

我希望你能帮助我:)。

2 个答案:

答案 0 :(得分:5)

问题似乎出现在您致电malloc()的行。

newPtr的类型为mazzo*,但您要为carta分配空间,这个空间太小了。

我认为它应该是newPtr=malloc(sizeof(mazzo));

答案 1 :(得分:0)

虽然这可能不适合您,但最好还是使用C ++。在其众多软件工程优势中,其new用于分配内存的习惯用法可以防止出现这种错误,因为您必须明确使用对象类型:newPtr = new mazzo;