Zatharan Zatharan - 2 months ago 37
C++ Question

c++ debug break exception

I'm using visual studio to code in C++

I have the following code

// 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;

In theory everything should work but when I try to launch with the local debugger error message

How do I debug it?


'tab' pointer points to memory allocated in the stack not in the heap, so memory will be freed automatically after function exit. Calling of

delete[] tab;

is wrong. No need to call it, memory will be automatically freed.

*tab = 0;

is wrong too, because defined that way, the pointer is 'const'. If you want to allocate memory in heap you should do:

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

and rest of your code will work.