删除数组在CodeBlocks上有效,但在Visual上无效
Deleting an array works on CodeBlocks but not on Visual
我正在构建一个类,并在某个时刻调用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上"工作",或者它是否在你的电脑和你朋友的电脑上工作,但在老师或客户的电脑上不工作,都无关紧要。如果出现诸如内存损坏之类的故障,请始终怀疑您的代码有问题。
相关文章:
- 我无法在Visual Studio代码中使用CIN输入答案,它说输入您的年龄,但它说只读文本编辑器如何解决这个问题?
- std::unique_ptr 在 GCC 中工作,但不能在 Visual Studio 中编译
- 代码在Visual Studio 2017中不起作用,但在VS代码中工作
- 默认/样板代码在Visual Studio 2017中给我错误.E1574.虚幻.但构建成功了
- 在Visual Studio中使用括号时编译错误,但在G ++ / CLang ++中传递
- 相同的代码在 Dev C++ 上编译,但在 Visual Studio 2017 上不编译
- 作为模板非类型参数的 C 字符串在 gcc 6.3 中有效,但在 Visual Studio 2017(x64 为 19
- 我的C 程序在CodeBlocks中提供了正确的结果,但在Visual Basic 2005 Express Edi
- 在 C++ Eclipse 中未定义对(错误)的引用,但在 Visual Studio 2015 中工作
- 为什么我的 c++ 程序在 Eclipse 中没有输出而终止,但在 Visual Studio 中工作
- 变量args SFINAE默认构造函数在clang中工作,但在Visual Studio 2015中失败
- 类模板继承无法在 GCC 中编译,但在 Visual Studio 中工作
- 在 G++ Ubuntu 中工作,但在 Visual Studio 中显示分段错误,在 Mac 中的代码块和 G++ 中
- 尝试编译OpenCV程序,但在Visual Studio 2012中出现LNK2038错误
- cpp文件不使用cl编译,但在Visual Studio中编译得很好
- g++编译器为表达式提供<<类型错误,但在Visual Studio中工作
- 64位exe在visual studio外崩溃,但在visual studio内工作
- 指向对象数组的c++指针在gnu c++中工作,但在visual studio中不工作
- C++类型转换运算符代码,在 Visual Studio 2012 中无法编译,但在 Visual Studio 2005 中工作正常
- 删除数组在CodeBlocks上有效,但在Visual上无效