Skip to content

Commit 862db64

Browse files
authored
BUG: Fix small memory access errors in ujson objToJSON.c (#33929)
1 parent 7aa710a commit 862db64

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

pandas/_libs/src/ujson/python/objToJSON.c

+8-9
Original file line numberDiff line numberDiff line change
@@ -1458,9 +1458,9 @@ char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc,
14581458

14591459
if (is_datetimelike) {
14601460
if (nanosecVal == get_nat()) {
1461-
len = 5; // TODO: shouldn't require extra space for terminator
1462-
cLabel = PyObject_Malloc(len);
1463-
strncpy(cLabel, "null", len);
1461+
len = 4;
1462+
cLabel = PyObject_Malloc(len + 1);
1463+
strncpy(cLabel, "null", len + 1);
14641464
} else {
14651465
if (enc->datetimeIso) {
14661466
if ((type_num == NPY_TIMEDELTA) || (PyDelta_Check(item))) {
@@ -1486,23 +1486,22 @@ char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc,
14861486
}
14871487
}
14881488
} else { // Fallback to string representation
1489-
PyObject *str = PyObject_Str(item);
1490-
if (str == NULL) {
1491-
Py_DECREF(item);
1489+
// Replace item with the string to keep it alive.
1490+
Py_SETREF(item, PyObject_Str(item));
1491+
if (item == NULL) {
14921492
NpyArr_freeLabels(ret, num);
14931493
ret = 0;
14941494
break;
14951495
}
14961496

1497-
cLabel = (char *)PyUnicode_AsUTF8(str);
1498-
Py_DECREF(str);
1497+
cLabel = (char *)PyUnicode_AsUTF8(item);
14991498
len = strlen(cLabel);
15001499
}
15011500

1502-
Py_DECREF(item);
15031501
// Add 1 to include NULL terminator
15041502
ret[i] = PyObject_Malloc(len + 1);
15051503
memcpy(ret[i], cLabel, len + 1);
1504+
Py_DECREF(item);
15061505

15071506
if (is_datetimelike) {
15081507
PyObject_Free(cLabel);

0 commit comments

Comments
 (0)