Skip to content

Instantly share code, notes, and snippets.

@isnullxbh
Created March 28, 2022 17:34
Show Gist options
  • Select an option

  • Save isnullxbh/081a128a6a0d902b525b9e5924a9f70f to your computer and use it in GitHub Desktop.

Select an option

Save isnullxbh/081a128a6a0d902b525b9e5924a9f70f to your computer and use it in GitHub Desktop.
Retrieve metadata for malloc
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <iostream>
struct Metadata
{
std::uint64_t data {};
auto size() const noexcept -> std::uint64_t { return (data & 0xFFFFFFFFFFFFFFF8) - sizeof(data); }
auto previousChunkInUse() const noexcept -> bool { return data & 0x01; }
auto allocatedWithMmap() const noexcept -> bool { return data & 0x02; }
};
static_assert(sizeof(Metadata) == sizeof(std::uint64_t));
int main()
{
auto* ptr = reinterpret_cast<char*>(malloc(0x00FFFF00));
Metadata metadata;
std::memcpy(&metadata, ptr - sizeof metadata, sizeof metadata);
std::cout << "Metadata:\n"
<< "size = " << (metadata.size() / (1 << 20)) << "MiB, "
<< "prev_chunk_in_use = " << metadata.previousChunkInUse() << ", "
<< "allocated_with_mmap = " << metadata.allocatedWithMmap()
<< std::endl;
std::free(ptr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment