Listing 4: A memory corruption example with a data structure that has a non-contiguous memory layout

typedef map<int, string> MapType;

// This function corrupts the memory
void offender(const void* ptr)
{
    const char trash[] = "TRASH THE MEMORY";
    ::memcpy(const_cast<void*>(ptr), trash, sizeof(trash));
}

// Prints map element. Although the code
// is correct, the function may crash when
// invoked from the main program
void printElem(const MapType& m, int i)
{
    MapType::const_iterator iter(m.find(i));

    if (iter != m.end())
        cout << iter->second << endl;
    else
        cout << "element not found" << endl;
}

int main()
{
    MapType m;

    // Initialize the map
    m.insert(MapType::value_type(1, "one"));
    m.insert(MapType::value_type(2, "two"));

    offender(&(m.find(1)->second));
    printElem(m, 1);

    return 0;
}
— End of Listing —