Unhandled exception at 0x771CC7C9 (ntdll.dll)

2

I have the following code in which an array is dynamically declared in a function. The following program compiles perfectly in Visual Studio 2013. However, during runtime the code breaks during printing the array, with the following error code:

Critical error detected c0000374 WaveEquation1D.exe has triggered a breakpoint. First-chance exception at 0x771CC7C9 (ntdll.dll) in WaveEquation1D.exe: 0xC0000374: A heap has been corrupted (parameters: 0x771F8890).

Unhandled exception at 0x771CC7C9 (ntdll.dll) in WaveEquation1D.exe: 0xC0000374: A heap has been corrupted (parameters: 0x771F8890).

What is going on? Please help

#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;

int solver(double i, double v, double c, double L, int Nx, double C1, double t);

int solver(double i, double v, double c, double L, int Nx, double C1, double t)
{
    double *msh = new double(Nx);
    double delta = L / Nx;

    int count = 0;
    for (int i = 0; i <= Nx; i++)
    {
        msh[i] = 0.0;
    }

    for (int i = 0; i <= Nx; i++)
    {
        msh[i] += delta*count;
        count++;
    }


    for (int i = 0; i <= Nx; i++)
    {
        cout << msh[i] <<endl;
    }
    delete[] msh;



//  

    return 0;
}



int main()
{
    cout << "Hello"<<endl;
    int size;

    int j;
    j = solver(1, 0, 0, 20.0, 20, 0, 1);
    _getch();
    return 0;
}
c++
dynamic

1 Answer

5
double *msh = new double(Nx);

should be

double *msh = new double[Nx];

otherwise you're just allocating a pointer on 1 double.

And the condition is wrong as other users commented

for (int i = 0; i <= Nx; i++)

should be

for (int i = 0; i < Nx; i++)

better solution: declare a vector of double

#include <vector>

std::vector<double> msh(Nx);  // instead of new double

no need to delete, of course, vector handles the deallocation automatically when variable goes out of scope.

and access your elements with msh.at(i) so if vector goes out of bounds an assertion is raised (performance suffers a bit, but bugs too)

answered on Stack Overflow Sep 5, 2016 by Jean-François Fabre • edited Sep 5, 2016 by Jean-François Fabre

User contributions licensed under CC BY-SA 3.0