Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8354699
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T09:37:56+00:00 2026-06-09T09:37:56+00:00

I am trying to write memory tracker in C++ by overloading new and delete

  • 0

I am trying to write memory tracker in C++ by overloading new and delete operator. But it is going into loop and calling new again and again. Following is my code.

#ifndef MEMORY_TRACKER_H_
#define MEMORY_TRACKER_H_

#pragma warning( disable : 4290 )
#pragma comment(lib, "Dbghelp.lib")

#include <Windows.h>
#include <malloc.h>
#include <map>
#include <iostream>
#include <DbgHelp.h>
#include <sstream>
#include <vector>


static const int MAX_TRACES     = 62;
static const int MAX_LENGTH     = 256;
static const int BUFFER_LENGTH  = (sizeof(SYMBOL_INFO) + MAX_LENGTH * sizeof(wchar_t) + sizeof(ULONG64) - 1) / sizeof(ULONG64);
static bool SYSTEM_INITIALIZED  = false;

typedef struct record_t {
    std::string symbol;
    std::string address;
    std::string filename;
    std::string linenumber;
} record;

typedef std::vector<record>              record_vec_t;
typedef std::pair<size_t, record_vec_t>  record_entry_t;
typedef std::map<size_t, record_entry_t> memory_record_t;

memory_record_t gMemoryRecord;

static record_vec_t GetCallStackDetails(const void* const* trace, int count ) {
    record_vec_t callStackVector;

    for (int i = 0; i < count; ++i) {
        ULONG64 buffer[BUFFER_LENGTH];
        DWORD_PTR frame           = reinterpret_cast<DWORD_PTR>(trace[i]);
        DWORD64 sym_displacement  = 0;
        PSYMBOL_INFO symbol       = reinterpret_cast<PSYMBOL_INFO>(&buffer[0]);
        symbol->SizeOfStruct      = sizeof(SYMBOL_INFO);
        symbol->MaxNameLen        = MAX_LENGTH;
        BOOL has_symbol           = SymFromAddr(GetCurrentProcess(), frame, &sym_displacement, symbol);
        DWORD line_displacement   = 0;
        IMAGEHLP_LINE64 line      = {};
        line.SizeOfStruct         = sizeof(IMAGEHLP_LINE64);
        BOOL has_line             = SymGetLineFromAddr64(GetCurrentProcess(), frame, &line_displacement, &line);

        record curr_rec;
        curr_rec.symbol = "(No Symbol)";

        std::stringstream formatter;        
        if (has_symbol) {
            curr_rec.symbol = symbol->Name;
            formatter.clear();
            formatter << " [0x" << trace[i] << "+" << sym_displacement << "]";     
            curr_rec.address = formatter.str();
        } else {
            formatter.clear();
            formatter << " [0x" << trace[i] << "]";
            curr_rec.address = formatter.str();
        }
        if (has_line) {
            formatter.clear();
            formatter << line.FileName;
            curr_rec.filename = formatter.str();

            formatter.clear();
            formatter << line.LineNumber;
            curr_rec.filename = formatter.str();
        }
        callStackVector.push_back(curr_rec);
    }
    return callStackVector;
}

static void addRecord(void *ptr, size_t size) {
    if ( SYSTEM_INITIALIZED == false ) {
        SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME | SYMOPT_LOAD_LINES);
        if (SymInitialize(GetCurrentProcess(), NULL, TRUE)) {
            SYSTEM_INITIALIZED = true;
        } else {
            SYSTEM_INITIALIZED = false;
            return;
        }
    }
    void* trace[MAX_TRACES];

    int count            = CaptureStackBackTrace(0, MAX_TRACES , trace, NULL);
    record_vec_t record  = GetCallStackDetails( trace, count);
    record_entry_t entry = std::make_pair( size, record);

    gMemoryRecord.insert(std::make_pair((size_t)ptr, entry));
}

static void deleteRecord(void *ptr ) {
    memory_record_t::iterator itr = gMemoryRecord.find((size_t)ptr);
    if ( itr != gMemoryRecord.end()) {
        gMemoryRecord.erase(itr);
    }
}

void dumpUnfreedMemory() {
    for ( memory_record_t::iterator itr = gMemoryRecord.begin(); itr != gMemoryRecord.end(); ++itr ) {
    }
}

// Overloading new operator
void* operator new ( size_t size ) throw ( std::bad_alloc ) {
    std::cout << " Overloaded new is called " << std::endl;
    void *ptr = (void *)malloc(size);
    addRecord(ptr, size);   

    return ptr;
}

// Overloading delete Operator
void operator delete ( void* ptr ) throw () { 
    std::cout << " Overloaded delete  is called " << std::endl;
    deleteRecord(ptr);
    free ( ptr );
}

#endif

following is the test file

#include "MemoryTracker.h"
int main ( int argc, char **argv) {
    int *ptr = new int;
    return 0;
}

it is going into loop on call of GetCallStackDetails, platform is windows

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T09:37:58+00:00Added an answer on June 9, 2026 at 9:37 am

    You’re overloading the global operator new, and std::vector<record> uses the default allocator, which calls operator new to allocate the memory. Which then calls your GetCallStack, which allocates a new vector ….

    One solution is to use a custom allocator in your vector, which pulls from a separate pool of memory, so that it doesn’t call your GetCallStack.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to write a C++ program to delete the shared memory segments.
i was trying to write a string to a memory stream, but failed with
I am trying to figure out how well the global memory write accesses of
I am trying write a function that generates simulated data but if the simulated
Trying to write out syslog entries containing strings but they don't register. // person.name
I'm trying to write xml data with XmlLite on buffer but couldn't got any
I am trying to write a parallel prefix scan on cuda by following this
I'm trying to write a response into a variable, and I can't figure out
I'm trying to write this down as concisely as possible, but it's not easy
I am trying to write a custom memory manager and right now I am

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.