From 1e3c7f3fd02e44860c078d60a5e274cd12eec200 Mon Sep 17 00:00:00 2001 From: Ronald van Elburg Date: Wed, 30 Sep 2020 15:11:10 +0200 Subject: [PATCH 1/2] Fix #51: Only return valid part of the buffer in the read function --- alsaaudio.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/alsaaudio.c b/alsaaudio.c index 75e628b..c0051ae 100644 --- a/alsaaudio.c +++ b/alsaaudio.c @@ -1051,6 +1051,7 @@ alsapcm_read(alsapcm_t *self, PyObject *args) { int res; int size = self->framesize * self->periodsize; + int sizeout; PyObject *buffer_obj, *tuple_obj, *res_obj; char *buffer; @@ -1106,16 +1107,20 @@ alsapcm_read(alsapcm_t *self, PyObject *args) } if (res <= 0) { + sizeout = 0; + } else { + sizeout = res * self->framesize; + } + #if PY_MAJOR_VERSION < 3 /* If the following fails, it will free the object */ - if (_PyString_Resize(&buffer_obj, 0)) + if (_PyString_Resize(&buffer_obj, sizeout)) return NULL; #else /* If the following fails, it will free the object */ - if (_PyBytes_Resize(&buffer_obj, 0)) + if (_PyBytes_Resize(&buffer_obj, sizeout)) return NULL; #endif - } res_obj = PyLong_FromLong(res); if (!res_obj) { From 5c481b4094a0cfd3337665509b50fb9e67b5dc63 Mon Sep 17 00:00:00 2001 From: Ronald van Elburg Date: Wed, 30 Sep 2020 15:58:19 +0200 Subject: [PATCH 2/2] Fix #51: Only return valid part of the buffer in the read function; avoid unnecesssary work by only changing size when needed --- alsaaudio.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/alsaaudio.c b/alsaaudio.c index c0051ae..2c587b7 100644 --- a/alsaaudio.c +++ b/alsaaudio.c @@ -1051,7 +1051,7 @@ alsapcm_read(alsapcm_t *self, PyObject *args) { int res; int size = self->framesize * self->periodsize; - int sizeout; + int sizeout = 0; PyObject *buffer_obj, *tuple_obj, *res_obj; char *buffer; @@ -1106,12 +1106,11 @@ alsapcm_read(alsapcm_t *self, PyObject *args) } } - if (res <= 0) { - sizeout = 0; - } else { + if (res > 0 ) { sizeout = res * self->framesize; } + if (size != sizeout) { #if PY_MAJOR_VERSION < 3 /* If the following fails, it will free the object */ if (_PyString_Resize(&buffer_obj, sizeout)) @@ -1121,7 +1120,8 @@ alsapcm_read(alsapcm_t *self, PyObject *args) if (_PyBytes_Resize(&buffer_obj, sizeout)) return NULL; #endif - + } + res_obj = PyLong_FromLong(res); if (!res_obj) { Py_DECREF(buffer_obj);