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

1 Answer

0 votes
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

/*
    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) {
    printf("Bit-level memory map (%zu bytes):\n", size);

    for (size_t i = 0; i < size; ++i) {

        // Convert each byte to an 8-bit binary string
        printf("Byte %02zu: ", i);

        for (int bit = 7; bit >= 0; --bit) {
            printf("%u", (data[i] >> bit) & 1);
        }

        printf("   (0x%02x)\n", data[i]);
    }
}

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

    if (!leakedBlock) {
        printf("Memory allocation failed.\n");
        return 1;
    }

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

    printf("Allocated memory at address: %p\n\n", (void*)leakedBlock);

    // 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 = NULL;

    printf("\nMemory leak created: pointer lost, "
           "block still allocated but unreachable.\n");

    return 0;
}


/*
run:

Allocated memory at address: 0x17b352a0

Bit-level memory map (8 bytes):
Byte 00: 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
...