eliemichel / LearnWebGPU-Code

The accompanying code of the Learn WebGPU C++ programming guide
https://eliemichel.github.io/LearnWebGPU
MIT License
114 stars 30 forks source link

step025 ,Memory leak on wgpuSurfaceGetCurrentTexture #51

Closed relaxslow closed 1 month ago

relaxslow commented 2 months ago

STACK OF 216 INSTANCES OF 'ROOT LEAK: <malloc in wgpuSurfaceGetCurrentTexture>':
3   dyld                                  0x197b0b154 start + 2476
2   cgame                                 0x102184a60 main + 704  main.c:469
1   libwgpu_native.dylib                  0x102bbb658 wgpuSurfaceGetCurrentTexture + 264
0   libsystem_malloc.dylib                0x197ccfa68 _malloc_zone_malloc_instrumented_or_legacy + 148 
====

below is part of my code

while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();
        // Get the next target texture view
        WGPUSurfaceTexture surfaceTexture;
        wgpuSurfaceGetCurrentTexture(surface, &surfaceTexture);

        if (surfaceTexture.status != WGPUSurfaceGetCurrentTextureStatus_Success)
        {
            continue; // Return NULL for failure case
        }
                // Create a view for this surface texture
        WGPUTextureViewDescriptor viewDescriptor;
        memset(&viewDescriptor, 0, sizeof(WGPUTextureViewDescriptor)); // Zero initialize the struct
        viewDescriptor.nextInChain = NULL;
        viewDescriptor.label = "Surface texture view";
        viewDescriptor.format = wgpuTextureGetFormat(surfaceTexture.texture);
        viewDescriptor.dimension = WGPUTextureViewDimension_2D;
        viewDescriptor.baseMipLevel = 0;
        viewDescriptor.mipLevelCount = 1;
        viewDescriptor.baseArrayLayer = 0;
        viewDescriptor.arrayLayerCount = 1;
        viewDescriptor.aspect = WGPUTextureAspect_All;

        // Create the texture view
        WGPUTextureView targetView = wgpuTextureCreateView(surfaceTexture.texture, &viewDescriptor);

        if (targetView == NULL)
        {
            continue;
        }
        ...
        ....

        // At the end of the frame, release the target texture view
        wgpuSurfacePresent(surface);
        wgpuTextureViewRelease(targetView);

        wgpuDevicePoll(device, false, NULL);

    }
eliemichel commented 1 month ago

Does it fix the issue to also release the surface texture with wgpuTextureRelease(surfaceTexture.texture); at the end of the loop?

relaxslow commented 1 month ago

yes ,wgpuTextureRelease(surfaceTexture.texture); solve the issue

eliemichel commented 1 month ago

That's curious because on my end I get a crash when releasing the surface texture, and the official spec suggests that wgpuSurfacePresent should take care of releasing whatever wgpuSurfaceGetCurrentTexture created.