I have a vector that I am trying to save between runs of my program, and I need to save it as a char* to memory. I decided to convert the bytes in my vector to be read as a char*, then read it again later on and read the bytes as a vector (of unchanged type), therefore saving it between runs. The problem is that this method does not seem to be working. I am managing to save the 24 bytes that contain the data about the vector, but the values that the vector contains are changed. I tried this method with an int, and it seems to work in that case.
I read some other posts on the subject, where the values in the vector were pointers. I understand why that wouldn't work, but in my case the values are std::pairs, so that shouldn't be the problem.
Edit: my code. I know for sure that the read() and write() functions work correctly. writeOrigin() and setUpOrigin() do things unrelated to the problem. When I run the code without adding anything to the vector, it works, but when I add any values to it, it crashes when I try to copy the value from _inodes to inodes. inode is a class that I made earlier, but the problem also occurs to the int in the pair.
void MyFs::writeInodes(){
static int count = 0;
int size = sizeof(inodes) + sizeof(std::pair<int, inode>) * inodes.capacity();
blkdevsim->write(SIZEOF_HEADER, sizeof(size), (char*)(&size));
blkdevsim->write(SIZEOF_HEADER + sizeof(size), size, (char*)(&inodes));
writeOrigin();
count++;
}
void MyFs::getInodes(){
static int count = 0;
if(0 == count){
count++;
int size = 0;
std::vector<std::pair<int, inode> >* _inodes;
blkdevsim->read(SIZEOF_HEADER, sizeof(size), (char*)(&size));
_inodes = (std::vector<std::pair<int, inode> >*)malloc(size);
blkdevsim->read(SIZEOF_HEADER + sizeof(size), size, (char*)_inodes);
for(unsigned int i = 0; i < _inodes->size(); i++){
std::cout << _inodes->at(i).first << std::endl;
inodes.push_back((*_inodes)[i]);
}
free(_inodes);
setUpOrigin();
}
}
void BlockDeviceSimulator::read(int addr, int size, char *ans) {
memcpy(ans, filemap + addr, size);
}
void BlockDeviceSimulator::write(int addr, int size, const char *data) {
memcpy(filemap + addr, data, size);
}