diff --git a/Python/codecs.c b/Python/codecs.c index 6d1ae651fa00058..84a0589c8e8317e 100644 --- a/Python/codecs.c +++ b/Python/codecs.c @@ -1426,19 +1426,19 @@ _PyCodec_SurrogateEscapeUnicodeEncodeError(PyObject *exc) return NULL; } - PyObject *res = PyBytes_FromStringAndSize(NULL, slen); - if (res == NULL) { + PyBytesWriter *writer = PyBytesWriter_Create(slen); + if (writer == NULL) { Py_DECREF(obj); return NULL; } - char *outp = PyBytes_AsString(res); + char *outp = PyBytesWriter_GetData(writer); for (Py_ssize_t i = start; i < end; i++) { Py_UCS4 ch = PyUnicode_READ_CHAR(obj, i); if (ch < 0xdc80 || ch > 0xdcff) { /* Not a UTF-8b surrogate, fail with original exception. */ Py_DECREF(obj); - Py_DECREF(res); + PyBytesWriter_Discard(writer); PyErr_SetObject(PyExceptionInstance_Class(exc), exc); return NULL; } @@ -1446,6 +1446,8 @@ _PyCodec_SurrogateEscapeUnicodeEncodeError(PyObject *exc) } Py_DECREF(obj); + PyObject *res = PyBytesWriter_Finish(writer); + // Py_BuildValue() propagates the exception if res is NULL return Py_BuildValue("(Nn)", res, end); }