I am trying to read a file and store the information in unsigned char arrays. However, my program seems to be overwriting variables.
ClassA header:
...
public:
ClassA(void);
void LoadMemoryBlock(char* block, int bank);
....
private:
unsigned char upperMemoryBank1[16384];
unsigned char upperMemoryBank2[16384];
....
ClassA file:
ClassA::ClassA(void)
{
}
...
void ClassA::LoadMemoryBlock(char* block, int bank)
{
if (bank == 1)
{
memcpy(upperMemoryBank1, block, 16384);
}
else if (bank == 2)
{
memcpy(upperMemoryBank2, block, 16384);
}
}
ClassB header:
...
private:
ClassA* classAobject;
...
ClassB file:
ClassB::ClassB()
{
classAobject = &ClassA();
...
}
...
ClassB::StoreFile(ifstream &file)
{
int position;
char fileData[16384];
position = file.tellg();
file.seekg(HEADER_SIZE, ios::beg);
position = file.tellg();
file.read(fileData, 16384);
position = file.tellg();
classAobject->LoadMemoryBlock(fileData, 1);
classAobject->LoadMemoryBlock(fileData, 2);
position = file.tellg(); // Crashes here
file.seekg(16384 + HEADER_SIZE, ios::beg);
...
}
Watching the position variable in my debugger shows that after the LoadMemoryBlock calls, it no longer shows 16400 like it did beforehand, but rather a random number that is different every time. Also, the file ifstream also is corrupted by the LoadMemoryBlock call. So I am guessing that memcpy is overwriting them.
I tried initializing my arrays differently, but now memcpy crashes!
ClassA header:
...
public:
ClassA(void);
void LoadMemoryBlock(char* block, int bank);
....
private:
unsigned char* upperMemoryBank1;
unsigned char* upperMemoryBank2;
....
ClassA file:
ClassA::ClassA(void)
{
upperMemoryBank1 = new unsigned char[16384];
upperMemoryBank2 = new unsigned char[16384];
}
...
void ClassA::LoadMemoryBlock(char* block, int bank)
{
if (bank == 1)
{
memcpy(upperMemoryBank1, block, 16384); // Crashes here
}
else if (bank == 2)
{
memcpy(upperMemoryBank2, block, 16384);
}
}
ClassB header:
...
private:
ClassA* classAobject;
...
ClassB file:
ClassB::ClassB()
{
classAobject = &ClassA();
...
}
...
ClassB::StoreFile(ifstream &file)
{
int position;
char* fileData = new char[16384];
position = file.tellg();
file.seekg(HEADER_SIZE, ios::beg);
position = file.tellg();
file.read(fileData, 16384);
position = file.tellg();
classAobject->LoadMemoryBlock(fileData, 1);
classAobject->LoadMemoryBlock(fileData, 2);
position = file.tellg();
file.seekg(16384 + HEADER_SIZE, ios::beg);
...
}
I thought that at least one, if not both, of these methods should work. What am I doing wrong?
EDIT: I have included the ClassA initialization above.
This is how I call the StoreFile method:
bool ClassB::Load(char* filename)
{
ifstream file(filename, ios::in|ios::binary);
if(file.is_open())
{
if(!StoreFile(file))
{
return false;
}
file.close();
return true;
}
printf("Could not open file: %s\n", filename);
return false;
}
classAobjectpoints to a valid object of classClassAat the beginning of that code?