删除数组在CodeBlocks上有效,但在Visual上无效

Deleting an array works on CodeBlocks but not on Visual

本文关键字:但在 Visual 无效 有效 CodeBlocks 删除 数组      更新时间:2023-10-16

我正在构建一个类,并在某个时刻调用delete。在代码块中它是有效的,而在Visual Studio 2013中则不然。

在我的课堂上,我有:

    private:
    bool sign;          // 0 if positive, 1 if negative
    int NumberSize;
    int VectorSize;
    int *Number;

然后我有了这个功能:

  void XXLint::Edit(const char* s)
{
// Get Size
this->NumberSize = strlen(s);
// Initialise Sign
if (s[0] == '-')
{
    this->sign = 1;
    s++;
}
else if (s[0] == '+') s++;
else this->sign = 0;
delete[] Number;  // Here the debugger gives me the error
//Get Vector Size
this->VectorSize = this->NumberSize / 4;
// Allocate Memory
this->Number = new int[this->VectorSize];
//Store the string into the number vector.
int location = this->VectorSize;
int current = this->NumberSize - 1;
while (location)
{
    int aux = 0;
    for (int i = 3; i >= 0 && current; i--)
    if (current - i >= 0)
        aux = aux * 10 + s[current - i] - '0';
    current -= 4;
    this->Number[location--] = aux;
}

}我确实读过这篇文章,它真的很有趣:D,但我不认为这就是错误的来源。为什么会发生这种错误?

查看此处:

this->Number = new int[this->VectorSize];
int location = this->VectorSize;

为了论证起见,假设this->VectorSize==10。所以location现在的值是10。然而,稍后您将在一个循环中执行此操作:

while (location)
{
   //...
   this->Number[location--] = aux;  // out of bounds!
}

您正在访问此->编号[10]。这是内存覆盖。不,位置在使用之前不会递减,因为它是递减后的,而不是递减前的。

当您在另一个编译器上编译程序,然后运行该程序时,如果该运行时检测到错误,总是询问您的代码。它是否在编译器X上"工作",或者它是否在你的电脑和你朋友的电脑上工作,但在老师或客户的电脑上不工作,都无关紧要。如果出现诸如内存损坏之类的故障,请始终怀疑您的代码有问题。

相关文章: