Skip to content

GC.GetTotalMemory occasionaly returns negative values #106712

Description

@AndreyAkinshin

Description

image

Reproduction Steps

No stable repro, but it happens from time to time in one of my applications.

Expected behavior

GC.GetTotalMemory should always return only non-negative values

Actual behavior

GC.GetTotalMemory occasionally returns negative values

Regression?

No response

Known Workarounds

No response

Configuration

Windows 11 x64, .NET SDK 8.0.204, net8.0

Other information

If anyone can advise on how to diagnose/debug this issue, I can collect additional information when it happens next time.

Activity

  1. ghost added
    needs-area-label
    on Aug 20, 2024
  2. added
    untriaged
    on Aug 20, 2024
  3. added and removed
    needs-area-label
    on Aug 20, 2024
  4. dotnet-policy-service commented on Aug 20, 2024

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/gc
    See info in area-owners.md if you want to be subscribed.

  5. removed
    untriaged
    on Aug 28, 2024
  6. added this to the 10.0.0 milestone on Aug 28, 2024
  7. firerain-fd commented on Jun 27, 2025

    @firerain-fd

    I have the same problem.

  8. kg commented on Jul 17, 2025

    @kg
    Contributor

    Is this while using NativeAOT or regular execution mode?

  9. kg commented on Jul 17, 2025

    @kg
    Contributor

    I audited the code and the internal GC total memory calculations are done per-heap using size_t instead of ssize_t/int64, so it makes sense that if we somehow got a very large calculated size, it would be negative. Getting a size that big should be impossible though, so that indicates some sort of rare bug in the underlying calculations. I couldn't spot any obvious cause, so it would be great if someone could offer more details on the reproduction scenario, even if you can't share an application with us.

    i.e.:

    • How big are your heaps when this isn't failing?
    • Is your application heavily multithreaded?
    • Is your application under load when you call this?
  10. AndreyAkinshin commented on Jul 21, 2025

    @AndreyAkinshin
    MemberAuthor

    In my case, this problem occurs in a small terminal app based on Terminal.Gui. Its typical memory footprint is about 1-2 MB. The app has several threads: Terminal.Gui threads + some background tasks in the user code for handling long-running operations, but it does not involve heavy multithreading. The app performs very basic tasks with a small number of allocations.

  11. kg commented on Jul 21, 2025

    @kg
    Contributor

    Test case I constructed fails instantly on NET9.

    using System.Threading;
    using System.Collections.Generic;
    
    bool Running = true;
    
    // See https://aka.ms/new-console-template for more information
    Console.WriteLine("Running...");
    
    var threads = new List<Thread>();
    for (int i = 0; i < 8; i++) {
        var thread = new Thread(ThreadMain);
        thread.Start();
        threads.Add(thread);
    }
    
    while (true) {
        var tm = GC.GetTotalMemory(false);
        if (tm < 0)
            throw new Exception($"Got total memory of {tm}");
        Thread.Yield();
    }
    
    void ThreadMain () {
        while (Running) {
            var s = "x";
            for (int i = 0; i < 1024; i++)
                s += i.ToString();
            Thread.Yield();
        }
    }
    Image
  12. added theissue type on Jul 21, 2025
  13. kg commented on Jul 21, 2025

    @kg
    Contributor

    Stepping through one iteration at a time shows that it fails after only a couple dozen steps. It looks like the result going negative might correlate with a GC, but Diagnostic Tools doesn't show a marker for the GC.

    I tried calling GetGCMemoryInfo before each iteration and it appears multiple GCs have happened so this might be some sort of race condition with the GC.
    Image

    EDIT: Further testing shows that this regressed sometime between NET6.0 and NET7.0. It is very hard to repro on 6 (it does repro eventually) but very easy in 7, 8 and 9.

  14. kg commented on Jul 22, 2025

    @kg
    Contributor

    Calling GetTotalMemory again will return a negative value even if you sleep first, so what's happening is that the GC heap is getting into a bad state of some sort. However, if you keep allocating eventually the GC heap will "recover" and become positive again. For example if you leave the threads going:

    Got total memory of -3665464
    Got total memory of 6809168
    Got total memory of 1422672 after sleeping 10ms
    Got total memory of 486960 after GetTotalMemory(true)
    

    However if you change the repro test to be single threaded:

    Running...
    Got total memory of -525416
    Got total memory of -517192
    Got total memory of -517192 after sleeping 10ms
    Got total memory of 421176 after GetTotalMemory(true)
    

    You can see that the forced GC from GetTotalMemory(true) corrected the state of the heap. Between the two GetTotalMemory calls the negative value moved towards zero slightly, probably from some sort of allocation that happened during the writeline call.

    Here is the single threaded repro. It takes longer to reproduce but does work:

    using System.Threading;
    using System.Collections.Generic;
    
    Console.WriteLine("Running...");
    
    while (true) {
        var s = "x";
        for (int i = 0; i < 1024; i++)
            s += i.ToString();
        Thread.Yield();
    
        var tm = GC.GetTotalMemory(false);
        if (tm < 0) {
            Console.WriteLine($"Got total memory of {tm}");
            tm = GC.GetTotalMemory(false);
            Console.WriteLine($"Got total memory of {tm}");
            tm = GC.GetTotalMemory(true);
            Console.WriteLine($"Got total memory of {tm} after GetTotalMemory(true)");
            return;
        }
    }
  15. kg commented on Jul 22, 2025

    @kg
    Contributor

    This does not reproduce using a debug or release mode build of corerun from latest main. If any of the reporters can test using one of the .NET 10 preview builds and see if it reproduces for you, I'd really appreciate it! It may be fixed already.

    EDIT: I was mistaken. The multithreaded repro does fail on net10, only the single-threaded one is fixed.

  16. mrsharm commented on Aug 7, 2025

    @mrsharm
    Contributor

    Thank you, @kg for the repro and thanks @AndreyAkinshin for reporting this.

    Here is what I have found:

    GCHeap::ApproxTotalBytesInUse is where the total memory is computed and the reason why we are observing negative total size is because the gen0 fragmentation size is much higher than the gen0 size; for gen0, the total size is estimated as gen0 size - the fragmentation on gen0 to remove the bytes not in use (https://github.com/dotnet/runtime/blob/d104e3e236dcd069ba56fffe2a10ba9d6cc647c9/src/coreclr/gc/gc.cpp#L51800)

    The printed lines from one such run from the multithreaded repro above before the failure is:

    ------------------------------------------------------------------------
    Gen0: TOTAL SIZE: -3643568, gen0_size: 31328, gen0_frag: 3674896, generation_free_list_space: 2245152, generation_free_obj_space: 481752
    GEN 1: gen_result: 997504, gen_size: 1003072, gen_frag: 5568, generation_free_list_space: 0, generation_free_obj_space: 5568
    GEN 2: gen_result: 284536, gen_size: 284536, gen_frag: 0, generation_free_list_space: 0, generation_free_obj_space: 0
    UOH GEN 3: uoh_gen_result: 0, uoh_gen_size: 0, uoh_gen_frag: 0, generation_free_list_space: 0, generation_free_obj_space: 0
    UOH GEN 4: uoh_gen_result: 8184, uoh_gen_size: 8184, uoh_gen_frag: 0, generation_free_list_space: 0, generation_free_obj_space: 0
    Total Size: -2353344
    ------------------------------------------------------------------------
    

    Looks like this code was introduced around the time we enabled regions: https://github.com/dotnet/runtime/pull/59283/files CC: @mangod9 -- the real question is why the gen0 fragmentation is that high; in this computation it's based on the sum of the free list space and free object space - both of which are substantially higher than the gen0 size. This is a regions specific issue btw - running this with segments is fine.

    Published a branch with these printfs: https://github.com/mrsharm/runtime/tree/musharm/Gen0FragPrint

  17. modified the milestones: 10.0.0, 11.0.0 on Aug 22, 2025
  18. added a commit that references this issue on Jul 27, 2026
    1103cab
  19. locked and limited conversation to collaborators on Aug 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

  • Status
    No status

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions