Memory leak when setting pixels with PixelArray

Issue #175 resolved
Former user created an issue

Was attempting to make a starfield animation (setting pixels moving across the screen at different speeds) with a PixelArray, and found increasing memory usage. Manual GC-calling did not solve the issue; found and replicated the problem:

The current workaround for me is to not use PixelArray and just use (short) lines to draw the star points.

Have replicated the issue with both Python 2.7.5 and 3.3.2.

Comments (15)

  1. Philip_Robinson

    For the WIndows XP Python 3.3.2 environment I had the pygame-1.9.2a0.win32-py3.3.msi build installed.

    I'm not sure which pygame releases I tried for the Ubuntu Python 3 or Windows XP Python 2.7.5 environments: I used a few! The same problem existed in all of them, and the same workaround (use lines instead of setting pixels) made the memory leak go away.

  2. cgohlke

    With the current development code this leaks:

    import pygame, sys
    from pygame.locals import *
    ScreenWidth, ScreenHeight = 640, 480
    Display = pygame.display.set_mode((ScreenWidth,ScreenHeight), 0, 32)
    pygame.display.set_caption('Memory Leak Test')
    while True:
        PixelArray = pygame.PixelArray(Display)
        PixelArray[ScreenWidth-1][ScreenHeight-1] = (255,255,255)
        del PixelArray
        for event in pygame.event.get():
            if event.type == QUIT:

    This does not leak memory:

    PixelArray[ScreenWidth-1, ScreenHeight-1] = (255,255,255)
  3. Philip_Robinson


    PixelArray[ScreenWidth-1][ScreenHeight-1] = (255,255,255)


    PixelArray[0][0] = (255,255,255)

    in the above demo leaks a lot less memory over time.

    It's almost as if the setting of a pixel is what allocates a block of memory (with size based on the co-ordinates), and the del command merely drops the reference to PixelArray variable itself and leaves this underlying grid intact.

  4. cgohlke

    This leaks too:


    This raises a SystemError: error return without exception set:

  5. Lenard Lindstrom

    I think I found the leak on line 1875 of pixelarray.c:

        PyObject *val = PyNumber_Index(op);

    Function PyNumber_Index returns a new reference, but val is not Py_DECREFed. I did not check for other leaks.

  6. cgohlke

    I tested the latest commits. The repr error is fixed but PixelArray[ScreenWidth-1][ScreenHeight-1] still leaks memory.

  7. Lenard Lindstrom

    I think the issue is solved, as the test case no longer shows excalating memory usage. Any other discovered leaks can be submitted as a new issue.

  8. Log in to comment