2016-11-28 3 views
0

私は理論上のすべてのもので、次のコード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; 
} 

が動作するはず持つC++

の中にコーディングするのVisual Studioを使用していますが、私は地元のデバッガerror message

で起動しようとすると、

どうすればデバッグできますか?

+1

あなたは 'new'を' delete'するだけなので、 'delete [] tab;'は間違っています。 – crashmstr

+0

また、プログラムにステップインしたり、最初の行にブレークポイントを設定したり、問題が発生するまで1行ずつステップしたりしてください。 – crashmstr

+0

ありがとうございました;) –

答えて

0

'tab'ポインタは、ヒープにないスタックに割り当てられたメモリを指します。したがって、関数終了後にメモリは自動的に解放されます。

delete[] tab; 

が間違っています。それを呼び出す必要はなく、メモリは自動的に解放されます。

*tab = 0; 

もそうだと定義されているので、ポインタは 'const'です。 あなたが行う必要がありますヒープにメモリを割り当てたい場合は、次の

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

とあなたのコードの残りの部分は動作します。