Discrepancy Between Constructor "output" and following print call to the object?

I am creating a Matrix class, and one of the constructors parses a string into a matrix. However, printing the result of the constructor (this->Print()) prints what I expect, and an <object_just_created>.Print() call returns bogus data. How is this even possible?
Thank you in advance, I have posted some snippets below.

------------------------------------------------------------------

Matrix::Matrix(const string &str)
{
// Parse a new matrix from the given string
Matrix r = Matrix::Parse(str);
nRows = r.nRows;
nCols = r.nCols;
NaM = r.IsNaM();
elements = new Element_t[nRows*nCols];

for ( Index_t i=0; i < nRows; i++ )
{
for ( Index_t j=0 ; j < nCols ; j++)
{
elements[i*nCols+j] = r.elements[i*nCols+j];
}
}

this->Print();
}

----------

in the driver program, here are the two successive calls

Matrix mm6("[1 2 3.8 4 5; 6 7 8 9 10; 20.4 68.2 1341.2 -15135 -80.9999]");
mm6.Print();
// mm6.Print() calls bogus data, -2.65698e+303 at each location. The matrix's
// underlying array is valid, because printing the addresses yields a block
// of memory 8 bits apart for each location
> underlying array is valid, because printing the addresses yields a block
> of memory 8 bits apart for each location
¿ah?


My guess is that you have a bad copy constructor, causing a double delete.
Or you manage to screw `Print()' (or `Parse()')

You shouldn't need to manually manage the memory, so make `elements' an std::vector or std::valarray.
> underlying array is valid, because printing the addresses yields a block
> of memory 8 bits apart for each location
¿ah?


The array is type double. Each element in a type-double array is 8 bits.

Print() and Parse() functions have proven to work correctly under identical conditions, but I'll look into the possibility of a double delete, however strange that seems.

This is for a course, with specific requirements.
> Each element in a type-double array is 8 bits.
Even if that were the case, what I mean is how were you able to check validity of the array.
Printing addresses would imply simply pointer arithmetic
The matrix's underlying array is valid, because printing the addresses yields a block of memory 8 bits apart for each location
The array is type double. Each element in a type-double array is 8 bits.


1
2
3
4
5
6
7
8
9
#include <iostream>

int main()
{
    double* ptr = nullptr ;

    for ( unsigned i=0; i<9 ; ++i )
        std::cout << &ptr[i] << '\n' ;
}
00000000
00000008
00000010
00000018
00000020
00000028
00000030
00000038
00000040


You tell the compiler how to treat the memory. The compiler generates code to reflect what you've asked it to assume. It does not reflect some underlying structure - there isn't anything but bits there.
Topic archived. No new replies allowed.