我必须工作并经常创建矩阵(我必须使用指针),所以我在C++中创建了一个函数来为其分配空间,并确保最后一个值设置为NULL。
应用程序在特定情况下会丢弃此错误(检测到glibc:内存损坏)。这是代码:

template<typename T> T *allocate(int size) {
    T *temp = new T[size];
    temp[size] = (T) NULL;
    return temp;
}

这有效:
unsigned char *tmp = allocate <unsigned char> (10);

但这丢掉了错误:
unsigned char **tmp = allocate <unsigned char *> (10);

那等于:
unsigned char **tmp = new unsigned char *[10];
tmp[10] = (unsigned char *) NULL;

哪个好为什么会丢弃此错误?

更新:感谢您的答复。我好瞎那是一个错误。但是崩溃的问题出在代码的另一部分,还因为我在数组分配的空间之外添加了NULL。

最佳答案

您不能这样做:

temp[size] = (T) NULL;

在这种情况下,大小将在您分配的最后一个之后索引存储位置,为此,请对其进行更改:
temp[size-1] = (T) NULL;

关于c++ - glibc检测到内存损坏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12922728/

10-12 15:04
查看更多