2012-01-12 114 views
0

FINAL_EDIT:发现问题,在for循环计数器,也被用作索引,大于数组元素的数量。关于它的奇怪的事情是,我没有收到分段错误,而是我提到的错误。那是为什么?malloc.c“sYSMALLOC:断言”与C++项目执行

谢谢你的帮忙!
_ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ _

我有一个项目在C + +得到这个错误(不总是),如果一个特定的全局变量作为一个大小的int阵列。

NEW EDIT_1->除了主函数,我还没有使用new运算符,我声明了一个指向类的对象的新指针数组。 像这样:

Student* test[NUM_AM]; 
for(int i=0; i<NUM_AM; i++) 
{ 
    test[i] = new Student(random_elements); 
} 

有没有办法找出导致该行?

的错误是这样(复制GDB的输出):

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. 

Program received signal SIGABRT, Aborted. 
0x00007ffff75563a5 in __GI_raise (sig=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64 
64 ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory. 
in ../nptl/sysdeps/unix/sysv/linux/raise.c 

同样的valgrind给出了这样的:

==6775== HEAP SUMMARY: 
==6775==  in use at exit: 560 bytes in 35 blocks 
==6775== total heap usage: 35 allocs, 0 frees, 560 bytes allocated 
==6775== 
==6775== LEAK SUMMARY: 
==6775== definitely lost: 560 bytes in 35 blocks 
==6775== indirectly lost: 0 bytes in 0 blocks 
==6775==  possibly lost: 0 bytes in 0 blocks 
==6775== still reachable: 0 bytes in 0 blocks 
==6775==   suppressed: 0 bytes in 0 blocks 
==6775== Rerun with --leak-check=full to see details of leaked memory 
==6775== 
==6775== For counts of detected and suppressed errors, rerun with: -v 
==6775== Use --track-origins=yes to see where uninitialised values come from 
==6775== ERROR SUMMARY: 806 errors from 2 contexts (suppressed: 4 from 4) 

谢谢您的时间。

NEW_EDIT2: 我跑与应用:

valgrind --leak-check=full --track-origins=yes ./out 
and NUM_AM = 25; 

这是我得到的输出是在这里引擎收录: here!

NEW_EDIT3: 我应该指出,该程序创建带有ID的学生,并在布尔数组和2个bool变量中为其分配真/假值。 变量NUM_AM用作声明为类成员的静态数组的索引。 此外,NUM_AM在搜索其ID时用于多种功能。

在NUM_AM> 22的情况下,即使在创建第一个学生后,也可能发生错误。 使用NUM_AM < = 21,我无法通过多次串行执行程序来重现错误。

+0

使用'--leak-check = full'和'track-origins = yes' ... – 2012-01-12 19:08:48

+0

它是不是告诉你那些806错误和2个上下文是什么? – 2012-01-12 19:12:19

+0

@KerrekSB:我已经更新了valgrind的输出作为额外的信息。 – Chris 2012-01-12 19:47:32

回答

1

很高兴你发现了你的bug的来源。关于你的最终问题

关于它的奇怪的事情是,我没有收到分段错误,而是我提到的错误。那是为什么?

如果在栈上分配您的阵列(例如,您test是堆叠阵列),访问超出数组边界的数据不会引发段故障。相反,您开始覆盖堆栈上的其他重要数据。堆栈包含:

  • 你所有的局部变量
  • 的返回地址的功能(这样函数知道返回)
  • 必要上一帧指针和其他的东西为正确的函数调用

请注意,以上的部分或全部可能会在某种程度上进行优化。 延伸阅读:http://en.wikipedia.org/wiki/Call_stack