Created
March 28, 2022 17:34
-
-
Save isnullxbh/081a128a6a0d902b525b9e5924a9f70f to your computer and use it in GitHub Desktop.
Retrieve metadata for malloc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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