c 2b 2b debug memory allocation

Solutions on MaxInterview for c 2b 2b debug memory allocation by the best coders in the world

showing results for - "c 2b 2b debug memory allocation"
María
26 Oct 2018
1// use valgrind for linux
2// use -fmudflap -lmudflap options with gcc, then start your program with MUDFLAP_OPTIONS=-print-leaks ./my_program.
3
4template<typename T>
5struct track_alloc : std::allocator<T> {
6    typedef typename std::allocator<T>::pointer pointer;
7    typedef typename std::allocator<T>::size_type size_type;
8
9    template<typename U>
10    struct rebind {
11        typedef track_alloc<U> other;
12    };
13
14    track_alloc() {}
15
16    template<typename U>
17    track_alloc(track_alloc<U> const& u)
18        :std::allocator<T>(u) {}
19
20    pointer allocate(size_type size, 
21                     std::allocator<void>::const_pointer = 0) {
22        void * p = std::malloc(size * sizeof(T));
23        if(p == 0) {
24            throw std::bad_alloc();
25        }
26        return static_cast<pointer>(p);
27    }
28
29    void deallocate(pointer p, size_type) {
30        std::free(p);
31    }
32};
33
34typedef std::map< void*, std::size_t, std::less<void*>, 
35                  track_alloc< std::pair<void* const, std::size_t> > > track_type;
36
37struct track_printer {
38    track_type * track;
39    track_printer(track_type * track):track(track) {}
40    ~track_printer() {
41        track_type::const_iterator it = track->begin();
42        while(it != track->end()) {
43            std::cerr << "TRACK: leaked at " << it->first << ", "
44                      << it->second << " bytes\n";
45            ++it;
46        }
47    }
48};
49
50track_type * get_map() {
51    // don't use normal new to avoid infinite recursion.
52    static track_type * track = new (std::malloc(sizeof *track)) 
53        track_type;
54    static track_printer printer(track);
55    return track;
56}
57
58void * operator new(std::size_t size) throw(std::bad_alloc) {
59    // we are required to return non-null
60    void * mem = std::malloc(size == 0 ? 1 : size);
61    if(mem == 0) {
62        throw std::bad_alloc();
63    }
64    (*get_map())[mem] = size;
65    return mem;
66}
67
68void operator delete(void * mem) throw() {
69    if(get_map()->erase(mem) == 0) {
70        // this indicates a serious bug
71        std::cerr << "bug: memory at " 
72                  << mem << " wasn't allocated by us\n";
73    }
74    std::free(mem);
75}
76
77int main() {
78    std::string *s = new std::string;
79        // will print something like: TRACK: leaked at 0x9564008, 4 bytes
80}