summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorstratakis <cstratak@redhat.com>2019-03-06 15:14:06 +0100
committerVictor Stinner <vstinner@redhat.com>2019-03-06 15:14:06 +0100
commit098b139816f379271b8d4de2561b5805dd47d229 (patch)
treea9d5a40aaa91b652e8fea32c306a9fe8fdca554b
parentb2aefd77e1da438aed649d018d6aa504ec35eac8 (diff)
downloadcpython-git-098b139816f379271b8d4de2561b5805dd47d229.tar.gz
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 19b52545df898ec911c44e29f75badb902924c0 to fix it.
-rw-r--r--Modules/_ctypes/cfield.c26
1 files changed, 9 insertions, 17 deletions
diff --git a/Modules/_ctypes/cfield.c b/Modules/_ctypes/cfield.c
index 46f041b00e..1b495fc9ac 100644
--- a/Modules/_ctypes/cfield.c
+++ b/Modules/_ctypes/cfield.c
@@ -1291,24 +1291,16 @@ U_set(void *ptr, PyObject *value, Py_ssize_t length)
static PyObject *
s_get(void *ptr, Py_ssize_t size)
{
- PyObject *result;
- size_t slen;
+ Py_ssize_t i;
+ char *p;
- result = PyString_FromString((char *)ptr);
- if (!result)
- return NULL;
- /* chop off at the first NUL character, if any.
- * On error, result will be deallocated and set to NULL.
- */
- slen = strlen(PyString_AS_STRING(result));
- size = min(size, (Py_ssize_t)slen);
- if (result->ob_refcnt == 1) {
- /* shorten the result */
- _PyString_Resize(&result, size);
- return result;
- } else
- /* cannot shorten the result */
- return PyString_FromStringAndSize(ptr, size);
+ p = (char *)ptr;
+ for (i = 0; i < size; ++i) {
+ if (*p++ == '\0')
+ break;
+ }
+
+ return PyBytes_FromStringAndSize((char *)ptr, (Py_ssize_t)i);
}
static PyObject *