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 *) 0xfe开发者_JAVA技巧edface;
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 assigns page[4]
to 0xfeedface
, 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 Block
on the stack, its destructor is called when it goes out of scope.
It's hard to tell what's wrong, because you show too little code.
However, the Rule Of Three says that, when a class has either a destructor, copy constructor, or an assignment operator, then it very likely needs all three of them.
With that in mind, your SSDSim::Block
class looks very suspicious. What does that destructor do that needs to be done but doesn't warrant taking care of copying?
You need to show the code for Block::read()
, but I think it's a safe bet that you're attempting to access the item returned from getting an element from the map
with the key 4
when there is no such element in the map.
(Your commented line adds one, so it works in that case).
精彩评论