Skip to content

Commit 0e21777

Browse files
authored
BUG: Fix Memory Leak in to_json (#62210)
1 parent 49d1d75 commit 0e21777

File tree

1 file changed

+40
-7
lines changed

1 file changed

+40
-7
lines changed

pandas/_libs/src/datetime/pd_datetime.c

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,23 @@ static int convert_pydatetime_to_datetimestruct(PyObject *dtobj,
5555
out->month = 1;
5656
out->day = 1;
5757

58-
out->year = PyLong_AsLong(PyObject_GetAttrString(obj, "year"));
59-
out->month = PyLong_AsLong(PyObject_GetAttrString(obj, "month"));
60-
out->day = PyLong_AsLong(PyObject_GetAttrString(obj, "day"));
58+
tmp = PyObject_GetAttrString(obj, "year");
59+
if (tmp == NULL)
60+
return -1;
61+
out->year = PyLong_AsLong(tmp);
62+
Py_DECREF(tmp);
63+
64+
tmp = PyObject_GetAttrString(obj, "month");
65+
if (tmp == NULL)
66+
return -1;
67+
out->month = PyLong_AsLong(tmp);
68+
Py_DECREF(tmp);
69+
70+
tmp = PyObject_GetAttrString(obj, "day");
71+
if (tmp == NULL)
72+
return -1;
73+
out->day = PyLong_AsLong(tmp);
74+
Py_DECREF(tmp);
6175

6276
// TODO(anyone): If we can get PyDateTime_IMPORT to work, we could use
6377
// PyDateTime_Check here, and less verbose attribute lookups.
@@ -70,10 +84,29 @@ static int convert_pydatetime_to_datetimestruct(PyObject *dtobj,
7084
return 0;
7185
}
7286

73-
out->hour = PyLong_AsLong(PyObject_GetAttrString(obj, "hour"));
74-
out->min = PyLong_AsLong(PyObject_GetAttrString(obj, "minute"));
75-
out->sec = PyLong_AsLong(PyObject_GetAttrString(obj, "second"));
76-
out->us = PyLong_AsLong(PyObject_GetAttrString(obj, "microsecond"));
87+
tmp = PyObject_GetAttrString(obj, "hour");
88+
if (tmp == NULL)
89+
return -1;
90+
out->hour = PyLong_AsLong(tmp);
91+
Py_DECREF(tmp);
92+
93+
tmp = PyObject_GetAttrString(obj, "minute");
94+
if (tmp == NULL)
95+
return -1;
96+
out->min = PyLong_AsLong(tmp);
97+
Py_DECREF(tmp);
98+
99+
tmp = PyObject_GetAttrString(obj, "second");
100+
if (tmp == NULL)
101+
return -1;
102+
out->sec = PyLong_AsLong(tmp);
103+
Py_DECREF(tmp);
104+
105+
tmp = PyObject_GetAttrString(obj, "microsecond");
106+
if (tmp == NULL)
107+
return -1;
108+
out->us = PyLong_AsLong(tmp);
109+
Py_DECREF(tmp);
77110

78111
if (PyObject_HasAttrString(obj, "tzinfo")) {
79112
PyObject *offset = extract_utc_offset(obj);

0 commit comments

Comments
 (0)