<分区>
我已经使用 new 分配了 5 个 int 空间,并尝试访问超出分配边界的 (array[size] = 2; )。理想情况下,它应该抛出一些错误,但事实并非如此。
int size = 5;
int* array = new int[size];
array[1] = 2;
//If I uncomment below line it gives me error
//array[size] = 2;
cout << array[1] << endl;
// Why this is not an problem
cout << array[size] << endl;
delete[] array;
但是当我试图删除这个分配的空间时,它显示了这个错误。
*** glibc detected *** /home/workspace/PracticeC++/Debug/PracticeC++: free(): invalid next size (fast): 0x08add008 ***
PracticeC++: malloc.c:2451: 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.
当我在评论 array[size] = 2; 行后尝试删除时,它工作正常。我无法理解这种奇怪的行为。根据我的理解,delete[] 运算符具有有关数组大小的信息,因此它不应超出该大小,并且此错误与我们尝试删除相同内存两次或未分配的情况有关我们。谁能告诉我这个错误背后的原因。