FINAL_EDIT:发现问题,在 for 循环中,也用作索引的计数器大于数组元素的数量。奇怪的是,我没有收到段错误,而是我提到的错误。为什么会这样?
感谢您的帮助!
_____________________________
我有一个用 C++ 编写的项目,我收到此错误(并非总是如此),如果一个特定的全局变量充当 int
数组的大小。
NEW EDIT_1->我根本没有使用 new
运算符,除了我声明一个新的类对象指针数组的 main 函数。
像这样:
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;
这是我在 pastebin 中得到的输出: here!
NEW_EDIT3: 我应该提一下,该程序创建了具有 ID 的学生,并在 bool 数组和 2 个 bool 变量中为他们分配了真/假值。 变量 NUM_AM 用作声明为类成员的静态数组的索引。 此外,NUM_AM 在搜索其 ID 时用于多个函数。
当 NUM_AM > 22 时,即使在第一个学生创建之后也可能发生错误。 对于 NUM_AM < = 21,我无法通过程序的多次串行执行来重现错误。
最佳答案
很高兴您找到了问题的根源。关于你的最后一个问题
The weird thing about it, was that I wasn't receiving segmentation fault and instead the error I've mentioned. Why was that?
如果您在堆栈上分配您的数组(例如,您的 test
是一个堆栈数组),访问超出数组边界的数据不会引发段错误。相反,您开始覆盖堆栈中的其他重要数据。堆栈包含:
- 你所有的局部变量
- 函数的返回地址(以便函数知道返回到哪里)
- 前一帧指针和正确函数调用所需的其他内容
请注意,上述部分或全部可能会在某种程度上进行优化。 进一步阅读:http://en.wikipedia.org/wiki/Call_stack
关于c++ - malloc.c "sYSMALLOC: Assertion"与 C++ 项目一起执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8840785/