C++调试中断异常

C++调试中断异常

问题描述:

我使用Visual Studio代码C++C++调试中断异常

我有以下代码

// fondamentaux C++.cpp : Defines the entry point for the console application. 

#include "stdafx.h" 
#include <iostream> 

using namespace std; 

int main() 
{//initialisation des variables 

     int total{ 0 }; 
     int tab[5]{ 11,22,33,44 }; 

//on double la valeur de l'index pour additionner les valeurs entre elles 

(*tab) = 2; 

//boucle pour additionner les valeurs entre elles 
     for (int i = 0; i < sizeof(tab); i++) 
     { 
      total += *(tab + i); 
     } 

//libérationn de l'espace mémoire 
     delete[] tab; 
     *tab = 0; 


//affichage du total 
     cout << "total = " << total << "\n"; // le total est 121 
     return 0; 
} 

在理论上就可以工作了,但是当我尝试用本地调试器推出error message

如何调试?

+1

你只''删除'你'新'',所以'删除[]选项卡;'是不正确的。 – crashmstr

+0

另外,进入你的程序或在第一行设置一个断点,然后逐行逐行,直到你看到问题。 – crashmstr

+0

感谢它的工作;) –

“tab”指针指向堆栈中分配的内存,而不是在堆中,因此内存将在函数退出后自动释放。调用

delete[] tab; 

是错误的。无需调用它,内存将被自动释放。

*tab = 0; 

也是错误的,因为定义了这种方式,指针是'const'。 如果你想分配的堆内存,你应该做的:

int* tab = new int[5]{ 11,22,33,44 }; 

和你的代码的其余部分将正常工作。