内存动态分配问题:主要:malloc.c:3096:sYSMALLOc [英] Problems with memory dynamic allocation: main: malloc.c:3096: sYSMALLOc
问题描述
我正在编写一个简单的函数来创建一个代表一副纸牌的列表. 这是结构的定义
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->nextPtr=sMazzoPtr;
sMazzoPtr=newPtr;
}
}
return sMazzoPtr;
}
GCC不会给我任何编译时错误,但是当我执行程序时,这就是输出
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
我也尝试过Valgrind,但我无法弄清楚代码中的错误.
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==
我希望你能帮助我:)
推荐答案
问题似乎出在您呼叫malloc()
的那一行.
The problem appears to be at the line where you call malloc()
.
newPtr
的类型为mazzo*
,但是您正在为carta
分配空间,该空间太小.
newPtr
is of type mazzo*
, but you are allocating space for a carta
, which is too small.
我认为应该是newPtr=malloc(sizeof(mazzo));
这篇关于内存动态分配问题:主要:malloc.c:3096:sYSMALLOc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!