C++ 删除数组对代码块有效,但对视觉块无效
我正在构建一个类,在某个时候我调用delete。在代码块中它可以工作,而在VisualStudio2013中则不行 在我的班上,我有:C++ 删除数组对代码块有效,但对视觉块无效,c++,class,visual-studio-2013,codeblocks,dynamic-allocation,C++,Class,Visual Studio 2013,Codeblocks,Dynamic Allocation,我正在构建一个类,在某个时候我调用delete。在代码块中它可以工作,而在VisualStudio2013中则不行 在我的班上,我有: private: bool sign; // 0 if positive, 1 if negative int NumberSize; int VectorSize; int *Number; 那么我有这个功能: void XXLint::Edit(const char* s) { // Get S
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;
}
}
我确实读过这篇文章,它真的很有趣:但我不相信这就是错误的来源。
为什么会发生此错误?请看这里:
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上“起作用”,或者它是否在您的计算机和您朋友的计算机上起作用,而不是在教师或客户的计算机上起作用,这并不重要。如果出现诸如内存损坏之类的故障,请始终怀疑代码有问题。您可能有未定义的行为,因为您没有实现赋值运算符和复制构造函数。堆损坏可能意味着您双重释放或覆盖了缓冲区的边缘。您可能会发现一个有趣的问题阅读。@taigi tanaka-
这两种方法在没有bug的代码块中都能很好地工作
如果在Visual Studio中运行时出现错误,那么即使在代码块(实际上是g++)中,您也会有bug,工作得不好。当你犯了诸如破坏记忆之类的错误时,任何事情都有可能发生,包括让事情看起来“起作用”。所以你很幸运,Visual Studio指出你的代码有问题。你应该发布真实的代码,而不仅仅是调用new[]和delete[]。new[]或delete[]没有什么问题——正是这两个调用之间的操作破坏了内存。我相信如果你写了一个程序,它所做的只是一个新的[],然后删除[],你不会看到任何错误。所以是你没有展示给我们的代码导致了这个问题。