2016-11-28 91 views
0

我使用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

感謝它的工作;) –

回答

0

「tab」指針指向堆棧中分配的內存,而不是在堆中,因此內存將在函數退出後自動釋放。調用

delete[] tab; 

是錯誤的。無需調用它,內存將被自動釋放。

*tab = 0; 

也是錯誤的,因爲定義了這種方式,指針是'const'。 如果你想分配的堆內存,你應該做的:

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

和你的代碼的其餘部分將正常工作。