chup
chup

Reputation: 79

std::unordered_map how to free struct created with malloc. Are 2 queries into the map required?

The following block of code seems to run fine Generates:

Add 1000 things _MyMap now holds [1000] things _MyMap free'd and erased. size now [0]

#include <unordered_map>
#include <iostream>

typedef struct _entry
{
    int now;
} ENTRY, * PENTRY;

std::unordered_map<int, PENTRY> _MyMap;
typedef std::unordered_map<int, PENTRY>::iterator itEntry;

int Now()
{
    return 10;
}

main function, adding comments because the site won't let me just add code

int main()
{   
    PENTRY pE = NULL;

    std::pair<itEntry, bool> r;

    printf("Add 1000 things\n");
    for (int i = 0; i < 1000; i++)
    {
        pE = (PENTRY)malloc(sizeof(ENTRY));
        pE->now = Now();

        r = _MyMap.insert(std::make_pair(i, pE));

        if (false == r.second)
        {
            printf("For some crazy reason its already there\n");
            continue;
        }
    }

    // OK, theres probably 1000 things in there now
    printf("_MyMap now holds [%u] things\n", _MyMap.size() );

    // The following seems stupid, but I don't understand how to free the memory otherwise
    for (int i = 0; i < 1000; i++)
    {
        // first query
        auto it = _MyMap.find(i);

        // if malloc failed on an attempt earlier this could be NULL right?
        // I've had free impls crash when given NULL, so I check.
        if (it != _MyMap.end() &&
            NULL != it->second)
            free(it->second);

        // second query
        _MyMap.erase(i);
    }

    printf("_MyMap free'd and erased.  size now [%u]\n", _MyMap.size());

    return 0;
}

Questions are inline in the comments

Upvotes: 2

Views: 485

Answers (1)

David Schwartz
David Schwartz

Reputation: 182769

You probably want this:

auto it = _Map.find(idUser);    
if (it != _Map.end())
{
    free(it->second);
    _Map.erase (it);
}

But it's really not a good idea to store a raw pointer in a collection this way. You should, ideally, just store the data directly in the map rather than storing a pointer to it. Otherwise, use std::unique_ptr so that the destruction of the pointer automatically frees the data.

Upvotes: 3

Related Questions