问题描述
请考虑以下数据结构,以表的形式管理内存缓冲区:
#include <cstdlib>
#include <cstring>
#include <unordered_map>
class BufferItem {
char* data = nullptr;
size_t data_size = 0;
public:
BufferItem () = default;
BufferItem (size_t size) : data_size(size) {
data = (char*) std::calloc (size,1);
printf("calloc %p\n",data);
}
~BufferItem () { std::free (data); }
inline bool ok () { return data != nullptr; }
};
class Buffer {
public:
using key_t = const char*;
private:
std::unordered_map<key_t,BufferItem> data;
public:
inline bool exists (key_t key) { return data.find (key) != data.end(); }
inline bool create (key_t key,size_t size) {
if (!exists (key)) data[key] = BufferItem (size);
return data[key].ok();
}
};
/* somewhere outside */
Buffer buf;
buf.create("ip_buf",16);
buf.create("port_buf",16);
由于某些原因,calloc()
返回相同的地址:
calloc 000000000338e800
calloc 000000000338e800
为什么会这样?我使用MinGW64 gcc 10.1.0构建。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)