How to create a memory leak and show the bit‑level memory map of the leaked block in C++

1 Answer

0 votes
#include <iostream>
#include <bitset>
#include <cstdint>
#include <iomanip>

/*
    This program demonstrates how to:
    1. Allocate a block of memory dynamically
    2. Fill it with known values
    3. Display a full bit‑level memory map of the allocated bytes
    4. Intentionally create a memory leak by losing the pointer

    IMPORTANT:
    A memory leak cannot be inspected *after* it leaks,
    because the pointer is lost. So we inspect the memory
    BEFORE leaking it.
*/

// Print a bit-level memory map of a memory block
void printMemoryMap(const uint8_t* data, size_t size) {
    std::cout << "Bit-level memory map (" << size << " bytes):\n";

    for (size_t i = 0; i < size; ++i) {
        // Convert each byte to an 8-bit binary string
        std::bitset<8> bits(data[i]);

        std::cout << "Byte " << std::setw(2) << i << ": "
                  << bits << "   (0x"
                  << std::hex << std::setw(2) << std::setfill('0')
                  << static_cast<int>(data[i])
                  << std::dec << ")\n";
    }
}

int main() {
    // Allocate memory (this block will be intentionally leaked)
    size_t size = 8;
    uint8_t* leakedBlock = new uint8_t[size];

    // Fill memory with a recognizable pattern
    for (size_t i = 0; i < size; ++i) {
        leakedBlock[i] = static_cast<uint8_t>(i * 17);  // arbitrary pattern
    }

    std::cout << "Allocated memory at address: "
              << static_cast<void*>(leakedBlock) << "\n\n";

    // Show the bit-level memory map BEFORE leaking the memory
    printMemoryMap(leakedBlock, size);

    // INTENTIONAL MEMORY LEAK:
    // We lose the only pointer to the allocated block.
    
    // This situation is primarily called a memory leak, 
    // specifically known as a lost pointer or orphaned memory.
    
    // It occurs when dynamically allocated memory (on the heap) 
    // cannot be accessed or freed because the program has lost 
    // the address stored in the pointer variable.
    
    leakedBlock = nullptr;

    std::cout << "\nMemory leak created: pointer lost, "
              << "block still allocated but unreachable.\n";
}


/*
run: 

Allocated memory at address: 0x882f2b0

Bit-level memory map (8 bytes):
Byte  0: 00000000   (0x00)
Byte 01: 00010001   (0x11)
Byte 02: 00100010   (0x22)
Byte 03: 00110011   (0x33)
Byte 04: 01000100   (0x44)
Byte 05: 01010101   (0x55)
Byte 06: 01100110   (0x66)
Byte 07: 01110111   (0x77)

Memory leak created: pointer lost, block still allocated but unreachable.

*/

 



answered May 10 by avibootz
...