I am having trouble determining why this C++ code breaks when using dynamic arrays with new / delete (C++ style), and why it does not break with malloc / free (C style).

Specifically, when using Visual Studio 2003 and the new / delete commands, I am getting the error "Debug Error: ... DAMAGE: after Normal block (#146) at 0x00375FE8."

I've attached the relevant code, including the recursive function TraverseBetas.

//Code continues..........

  //double *lvec;
  //lvec = new double(numrows);

  //double *uvec;
  //uvec = new double(numrows);

  double *lvec;
  lvec = (double*) malloc (numrows * sizeof(double));

  double *uvec;
  uvec = (double*) malloc (numrows * sizeof(double));

  for (int i = 0; i < numrows; i++)
    *(lvec + i) = i;
    *(uvec + i) = *(maxrhs + i) - 1;

  TraverseBetas(numrows, lvec, uvec, 0, &temp);

  //delete [] lvec;
  //lvec = NULL;

  //delete [] uvec;
  //uvec = NULL;


//Code continues..........

void TraverseBetas(int numrows, double *lvec, double *uvec, int recurselevel, rhsstruct ***current)
    int i;
    int lowermark = (int) lvec[recurselevel];
    int uppermark = (int) uvec[recurselevel];

    if (recurselevel == numrows - 1)
        for (i = lowermark; i <= uppermark; i++)
            cout << endl << "Testing... current value is: " << (*current)[i]->lbval;
        for (i = lowermark; i <= uppermark; i++)
            TraverseBetas(numrows, lvec, uvec, (recurselevel + 1), (rhsstruct ***) (*current + i));

What I can't understand is why it works when I use the following malloc & free commands, but not with (the currently commented out) new & delete commands. It breaks on this line: delete [] lvec; and ends up in dbgheap.c. Can anyone point me in the right direction?


Recommended Answers

All 2 Replies

double *lvec;
  lvec = new double(numrows);

That allocates you a single double, initialized with the value of numrows . In that case, you delete that double by: delete lvec; Anyhow, you need to do ...

// try allocating numrows doubles ...
double *lvec = new double [numrows];

// and eventually delete 
delete [] lvec;

Dear mitrmkar,

Thanks for your reply, I overlooked the obvious. Glad it wasn't something more serious!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.