I am new to C++ and I’m having trouble using a map correctly in class that I’m writing. Basically, when I make a new Block object in a test program and call its write method, the program totally shits itself and gives me a double free or corruption error. What is weird is that everything works fine if I uncomment that one line in the Block constructor. I’m guessing I’m missing some basic c++ knowledge but I’m not finding anything useful on google.
Block.h (includes not shown but they are there):
namespace SSDSim{
class Block{
public:
Block(uint block_num);
~Block(void);
void read(uint page_num);
void write(uint page_num, void *data);
void erase(void);
private:
uint block_num;
std::map<uint, void *> page_data;
};
}
Block.cpp:
#include "Block.h"
using namespace std;
using namespace SSDSim;
Block::Block(uint block){
//page_data[4]= (void *) 0xfeedface;
block_num= block;
}
...
void Block::write(uint page_num, void *data){
if (page_data.find(page_num) == page_data.end()){
page_data[page_num]= data;
} else{
cerr<<"Invalid write\n";
exit(1);
}
}
test.cpp:
#include <iostream>
#include "../Block.h"
using namespace std;
using namespace SSDSim;
int main(void){
Block b= Block(0);
b.write(0, (void *) 0xdeadbeef);
b.read(0);
// b.read(4);
return 0;
}
Are you sure the error isn’t when you call
read()? After all, your constructor assignspage[4]to0xfeedface, an arbitrary place in memory that could point to anything. If you try to then read that location in memory, bad things may happen.I would try to avoid creating pointers out of arbitrary addresses. Instead, test your program by making some object and passing its address to
page[4].The error could also be in your destructor. Since you are allocating a
Blockon the stack, its destructor is called when it goes out of scope.