c ++调试中断异常

时间:2016-11-28 14:45:58

标签: c++ visual-studio debugging breakpoints

我正在使用visual studio在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 个答案:

答案 0 :(得分:0)

'tab'指针指向不在堆中的堆栈中分配的内存,因此在函数退出后将自动释放内存。致电

delete[] tab;

错了。无需调用它,内存将自动释放。

*tab = 0;

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

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

其余的代码都可以使用。