Consider the following data structure for managing memory buffers as table:
#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);
For some reason, calloc()
returns same address:
calloc 000000000338e800
calloc 000000000338e800
Why does this happen? I build with MinGW64 gcc 10.1.0.