这个问题第一次遇到,感觉比较奇怪,大致的代码如下
void png::read(const std::string& fname) {
using chnk_ptr=void (*)(uint32_t, std::shared_ptr<char>);
static const std::unordered_map<std::string, chnk_ptr> chnk_lut = {
{ "IHDR", png::chnk_ihdr },
{ "PLTE", png::chnk_plte },
{ "IDAT", png::chnk_idat },
};
FILE * fp = fopen(fname.c_str(),"rb");;
if (!fp)
return;
// magic png header
char b_hdr[8];
fread(b_hdr, sizeof(b_hdr),1,fp);
if (std::memcmp("\x89\x50\x4e\x47\x0d\x0a\x1a\x0a", b_hdr, 8) != 0)
return;
// read chunks
// assuming none are incomplete
while (!feof(fp)) {
char b_len[4], b_type[5];
std::memset(b_type, 0, sizeof(b_type));
if(fread(b_len, 4,1,fp) !=1)
return;
if(fread(b_type, 4,1,fp) !=1)
return;
uint32_t c_len = big32(b_len);
std::cout << "hit chunk of size: " << c_len << std::endl;
std::shared_ptr<char> b_data = std::make_shared<char>(c_len);
if(fread(b_data.get(), c_len,1,fp) != 1)
return;
// ignore crc
fseek(fp, 4, std::ios_base::cur);
// check if chunk is in lut, if so call it
auto cback = chnk_lut.find(static_cast<char*>(b_type));
if (cback != chnk_lut.end())
(cback)->second(c_len, b_data);
}
m_val = true;
fclose(fp);
}
这是个解析png图像的代码,但是使用make_shared会莫名其妙的报segmentfault,vs下报wrote to memory after end of buffer运行时错误,但是换成用new的方式构造shared_ptr就是好的,不知道是为啥