'Executing c++ object file in command line gives different output than VScode debugger

I was following a youtube tutorial that made a simple memory allocation tracker by overriding the new and delete operators. It uses an object to keep track of the stats. Its pretty simple, here is the code

#include <iostream>

struct AllocationMetics
{
    uint32_t TotalAllocated = 0;
    uint32_t TotalFreed = 0;
    uint32_t TotalUsage() { return TotalAllocated - TotalFreed; }
};

static AllocationMetics s_AllocationMetrics;

void* operator new(size_t size)
{
    s_AllocationMetrics.TotalAllocated += size;
    return malloc(size);
}

void operator delete(void* memory, size_t size) noexcept
{
    s_AllocationMetrics.TotalFreed += size;
    std::cout << size << " added to total freed \n";
    free(memory);
}

void LogMemStat()
{
    std::cout << "Total memory allocated: " << s_AllocationMetrics.TotalAllocated << std::endl
        << "Total memory freed: " << s_AllocationMetrics.TotalFreed << std::endl
        << "Total memory usage: " << s_AllocationMetrics.TotalUsage() << std::endl << std::endl;
}

struct Object
{
    int x;
};

int main()
{
    LogMemStat();

    Object* obj = new Object;
    LogMemStat();

    delete obj;
    LogMemStat();

    return 0;
}

when I compile with g++20 on my Mac (running on M1, Monterey 12.2.1) via the command line and execute the object file, the output is

Total memory allocated: 0
Total memory freed: 0
Total memory usage: 0

Total memory allocated: 4
Total memory freed: 0
Total memory usage: 4

Total memory allocated: 4
Total memory freed: 0
Total memory usage: 4

indicating a memory leak. Now, in VScode, I put a breakpoint in the overriden delete operator to see if it visited the function. Sure enough, in VScode, using g++20 as well, It did visit the function. The output in the VScode terminal was this:

Total memory allocated: 0
Total memory freed: 0
Total memory usage: 0

Total memory allocated: 4
Total memory freed: 0
Total memory usage: 4

4 added to total freed 
Total memory allocated: 4
Total memory freed: 4
Total memory usage: 0

I've run into stuff like this before, but never this blatant. Could someone please shed light on what may be going on here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source