Re: class initialization problem, please help
On Sep 26, 5:04 am, zl2k <kdsfin...@gmail.com> wrote:
Here is a simplified piece of code of my program, it compiles
and runs fine. However, valgrind shows it has uninitialized
problem. What I am doing wrong?
You're misusing reinterpret_cast.
#ifndef DATA2_H
#define DATA2_H
class Data2{
public:
int regionId;
bool isLandscape;
double parameters[16];
Data2();
~Data2();
};
#endif
#include "data2.h"
#include <iomanip>
#include <fstream>
using namespace std;
Data2::Data2(): regionId(-1), isLandscape(false)
{
for (int i = 0; i < 16; i++)
parameters[i] = 1;
}
Data2::~Data2()
{
}
int main(){
char buffer[512] = "abc.bin";
ofstream myfile;
Data2 *dataArray = new Data2[10];
myfile.open (buffer, ios::out | ios::binary);
int *num = new int(10);
myfile.write((char*)num, sizeof(int));
myfile.write ((char*)dataArray, sizeof (Data2) * *num);
The casts in the two statements above are reinterpret_cast's;
you shouldn't be using them unless you really know what you are
doing. And you shouldn't be too surprised that valgrind finds
errors if you do use them.
In this particular case, the standard does guarantee that the
write's will work, despite the uninitialized memory reads, but
only because ofstream is guaranteed to access the data as bytes.
On the other hand, it doesn't say anything about what will
actually be written, and it doesn't guarantee that you will be
able to reread it---in practice, you may encounter problems
rereading it if you recompile the program with different
compiler options, or with a newer version of the compiler, and
you will almost certainly encouter problems trying to reread it
if you run the program on another machine.
Dumping bit images to disk doesn't work, except for temporary
files that you will reread later in the same program run.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34