Re: class initialization problem, please help
On 26 Sep, 13:37, zl2k <kdsfin...@gmail.com> wrote:
On Sep 26, 2:17 am, Triple-DES <DenPlettf...@gmail.com> wrote:
On 26 Sep, 05:04, zl2k <kdsfin...@gmail.com> wrote:
hi, there
Here is a simplified piece of code of my program, it compiles and run=
s
fine. However, valgrind shows it has uninitialized problem. What I am
doing wrong?
#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=
);
myfile.close();
delete num;
delete [] dataArray;
return 1;
}
Try the following:
int data2size = sizeof(Data2);
int membersize = sizeof(int) + sizeof(bool) + sizeof(double)*16;
What are these values on your system?
Does that tell you anything ? :)
DP
It's different! To make it simpler, the Data2 will only contains an
int and a bool, the data2size is 8 and membersize is 5. I am fine if
using 5 for output. The sizeof(ClassType) is bad, is it? Thanks a lot.
zl2k
You're onto something, but your conclusion is wrong I think. What I
wanted to show you was that the Data2 class may very well be larger
than the sum of its members (sizeof returns the number of bytes of the
object). So what are those extra bytes?
Put simply, they are "padding" inserted by the compiler so that it may
access the members of the class more efficiently. This is commonly
referred to as _alignment_. Naturally when you take the address of the
object and interpret it as a char*, you will expose the padding bytes.
Data2 possible object layout:
[ 0 ][ 1 ][ 2 ][ 3 ][ 4 ][ 5 ][ 6 ][ 7 ]
[ int (4 bytes) ][bool][ padding ]
The padding could be set to a special value by the compiler to
correspond to "uninitialized memory", or it could simply be garbage.
Hence, your binary file will have bytes with an unspecified value
written to it.
Class member alignment may vary depending on architecture and compiler
version, and even the settings of the compiler. This is covered by
James Kanze's post.
DP