Map Holding a void*

I'm writing a program to overload the new and delete operators. I'm doing this so that every time the new operator is called, it saves the info of the new pointer, along with its size in a map.

map<void*, size_t>

The problem that I am having, though, is that there is something wrong with the void pointer that I am creating using the malloc function. When I try to add these void pointers to my map, my program gets a EXC_BAD_ACCESS error. How can I add these newly allocated void pointers to my map without getting that error? Here's my program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <map>
#include <memory>

using namespace std;

/************************************************************/

static int totalBytes = 0;
static map<void*, size_t> locations;

class MemoryManager
{
public:
    MemoryManager() {}
    
    static void addLocationElement(void* ptr, size_t size)
    {
        totalBytes += size;
        locations.insert(pair<void*, size_t>(ptr, size));
    }
    
    static void removeLocationElement(void* ptr)
    {
        totalBytes -= locations[ptr];
        locations.erase(ptr);
    }
};

/************************************************************/

void* operator new(size_t sz)
{
    void* temp = (void*)malloc(sz);
    MemoryManager::addLocationElement(temp, sz);
    return temp;
}

void* operator new[](size_t sz)
{
    void* temp = malloc(sz);
    MemoryManager::addLocationElement(temp, sz);
    return temp;
}

void operator delete(void* todel)
{
    MemoryManager::removeLocationElement(todel);
    free(todel);
}

void operator delete[](void* todel)
{
    MemoryManager::removeLocationElement(todel);
    free(todel);
}

/************************************************************/

int main()
{
    string* a = new string("H");
    cout << locations[a];
}
Last edited on
So you want to supply a global replacement for new and you want your replacement to add the new pointer to a map. Do you think new gets called when adding something to a map?
hi .
I am a korean.

You want some help to
I don't know speak English
Would you understand?

1. program start
2. startup function
3. call new

and
4. locations memory alloc

so
step 4. call new -> operator new . Error.

I'm sorry for being not helpful
But I hope you have had an understanding

closed account (48bpfSEw)
yes, very strange the access violation!

may be you'll find an answer in the implementation of FastMM4BCB.cpp

http://read.pudn.com/downloads167/sourcecode/delphi_control/766105/FastMM4/CPP%20Builder%20Support/FastMM4BCB.cpp__.htm

I have no time...
Last edited on
Topic archived. No new replies allowed.