调试错误,在C ++中检测到堆损坏

时间:2017-10-25 15:42:17

标签: c++

我在我的一个职能中遇到了一个问题,

Contact& Contact::operator+=(long long phone)
{
    if (isValidPhonenumber(phone)) {
        long long* tmp = new long long[this->amtNumbers + 1];
        for (int i = 0; i < this->amtNumbers; i++) {
            tmp[i] = this->m_pNumber[i];
        }
        tmp[amtNumbers + 1] = phone;
        delete[] this->m_pNumber;
        this->m_pNumber = tmp;
        this->amtNumbers++;
        return *this;
    }
}

我认为导致这种情况的是tmp[amtNumbers + 1] = phone;。但我不明白为什么?我似乎已经分配了足够的内存。也许我在delete[] tmp;之后遗漏了this->m_pNumber = tmp;

但即便如此,

Contact& Contact::operator+=(long long phone)
{
    if (isValidPhonenumber(phone)) {
        long long* tmp = new long long[this->amtNumbers + 1];
        for (int i = 0; i < this->amtNumbers; i++) {
            tmp[i] = this->m_pNumber[i];
        }
        tmp[amtNumbers + 1] = phone;
        delete[] this->m_pNumber;
        this->m_pNumber = tmp;
        delete[] tmp;
        this->amtNumbers++;
        return *this;
    }
}

我遇到了溢出错误。想法,建议?这是一种数字类型,而不是字符;我不需要为空字符分配任何额外的东西。

1 个答案:

答案 0 :(得分:1)

您声明long long* tmp = new long long[this->amtNumbers + 1];,然后使用超出范围的tmp[amtNumbers + 1] = phone;。最大索引是this->amtNumbers,因为数组是0索引的。