Skip to content

Commit 098b139

Browse files
stratakisvstinner
authored andcommitted
bpo-36147: Fix a memory leak in ctypes s_get() (GH-12102)
The s_get() function leaks the result variable on low memory. Partially backport commit 19b5254 to fix it.
1 parent b2aefd7 commit 098b139

File tree

1 file changed

+9
-17
lines changed

1 file changed

+9
-17
lines changed

Modules/_ctypes/cfield.c

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1291,24 +1291,16 @@ U_set(void *ptr, PyObject *value, Py_ssize_t length)
12911291
static PyObject *
12921292
s_get(void *ptr, Py_ssize_t size)
12931293
{
1294-
PyObject *result;
1295-
size_t slen;
1294+
Py_ssize_t i;
1295+
char *p;
12961296

1297-
result = PyString_FromString((char *)ptr);
1298-
if (!result)
1299-
return NULL;
1300-
/* chop off at the first NUL character, if any.
1301-
* On error, result will be deallocated and set to NULL.
1302-
*/
1303-
slen = strlen(PyString_AS_STRING(result));
1304-
size = min(size, (Py_ssize_t)slen);
1305-
if (result->ob_refcnt == 1) {
1306-
/* shorten the result */
1307-
_PyString_Resize(&result, size);
1308-
return result;
1309-
} else
1310-
/* cannot shorten the result */
1311-
return PyString_FromStringAndSize(ptr, size);
1297+
p = (char *)ptr;
1298+
for (i = 0; i < size; ++i) {
1299+
if (*p++ == '\0')
1300+
break;
1301+
}
1302+
1303+
return PyBytes_FromStringAndSize((char *)ptr, (Py_ssize_t)i);
13121304
}
13131305

13141306
static PyObject *

0 commit comments

Comments
 (0)