Skip to content

Commit 3b4f958

Browse files
committed
Merge pull request matplotlib#3207 from dopplershift/fix_memory_leak
Fix memory leak in tostring_rgba_minimize(). (matplotlib#3197)
2 parents 655b078 + ef5f0ac commit 3b4f958

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

Diff for: src/_backend_agg.cpp

+14-10
Original file line numberDiff line numberDiff line change
@@ -2401,13 +2401,24 @@ RendererAgg::tostring_rgba_minimized(const Py::Tuple& args)
24012401
newheight = ymax - ymin;
24022402
int newsize = newwidth * newheight * 4;
24032403

2404-
unsigned char* buf = new unsigned char[newsize];
2405-
if (buf == NULL)
2404+
// NULL pointer causes Python to allocate uninitialized memory.
2405+
// We then grab Python's pointer to uninitialized memory using
2406+
// the _AsString() API.
2407+
unsigned int* dst;
2408+
2409+
#if PY3K
2410+
data = Py::Bytes(static_cast<const char*>(NULL), (int) newsize);
2411+
dst = reinterpret_cast<unsigned int*>(PyBytes_AsString(data.ptr()));
2412+
#else
2413+
data = Py::String(static_cast<const char*>(NULL), (int) newsize);
2414+
dst = reinterpret_cast<unsigned int*>(PyString_AsString(data.ptr()));
2415+
#endif
2416+
2417+
if (dst == NULL)
24062418
{
24072419
throw Py::MemoryError("RendererAgg::tostring_minimized could not allocate memory");
24082420
}
24092421

2410-
unsigned int* dst = (unsigned int*)buf;
24112422
unsigned int* src = (unsigned int*)pixBuffer;
24122423
for (int y = ymin; y < ymax; ++y)
24132424
{
@@ -2416,13 +2427,6 @@ RendererAgg::tostring_rgba_minimized(const Py::Tuple& args)
24162427
*dst = src[y * width + x];
24172428
}
24182429
}
2419-
2420-
// The Py::String will take over the buffer
2421-
#if PY3K
2422-
data = Py::Bytes((const char *)buf, (int) newsize);
2423-
#else
2424-
data = Py::String((const char *)buf, (int) newsize);
2425-
#endif
24262430
}
24272431

24282432
Py::Tuple bounds(4);

0 commit comments

Comments
 (0)