Skip to content

Commit 6d5ecc7

Browse files
committed
BUG: read_table and read_csv crash (pandas-dev#22748)
A missing null-pointer check made read_table and read_csv prone to crash on badly encoded text. Add null-pointer check.
1 parent 1a12c41 commit 6d5ecc7

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

doc/source/whatsnew/v0.24.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,7 @@ I/O
745745

746746
- :func:`read_html()` no longer ignores all-whitespace ``<tr>`` within ``<thead>`` when considering the ``skiprows`` and ``header`` arguments. Previously, users had to decrease their ``header`` and ``skiprows`` values on such tables to work around the issue. (:issue:`21641`)
747747
- :func:`read_excel()` will correctly show the deprecation warning for previously deprecated ``sheetname`` (:issue:`17994`)
748+
- :func:`read_csv()` and func:`read_table()` will throw UnicodeEncodeError and not coredump on badly encoded strings (:issue:`22748`)
748749
- :func:`read_csv()` will correctly parse timezone-aware datetimes (:issue:`22256`)
749750
- :func:`read_sas()` will parse numbers in sas7bdat-files that have width less than 8 bytes correctly. (:issue:`21616`)
750751
- :func:`read_sas()` will correctly parse sas7bdat files with many columns (:issue:`22628`)

pandas/_libs/src/parser/io.c

+5-1
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,11 @@ void *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read,
150150
return NULL;
151151
} else if (!PyBytes_Check(result)) {
152152
tmp = PyUnicode_AsUTF8String(result);
153-
Py_XDECREF(result);
153+
Py_DECREF(result);
154+
if (tmp == NULL) {
155+
PyGILState_Release(state);
156+
return NULL;
157+
}
154158
result = tmp;
155159
}
156160

pandas/tests/io/parser/c_parser_only.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
import pandas.util.testing as tm
1919
import pandas.util._test_decorators as td
2020
from pandas import DataFrame
21-
from pandas.compat import StringIO, range, lrange
21+
from pandas.compat import BytesIO, StringIO, range, lrange
22+
from io import TextIOWrapper
2223

2324

2425
class CParserTests(object):
@@ -55,6 +56,13 @@ def test_buffer_rd_bytes(self):
5556
except Exception:
5657
pass
5758

59+
def test_buffer_rd_bytes_bad_unicode(self, method):
60+
# Regression test for #22748
61+
b = BytesIO(b"\xB0")
62+
t = TextIOWrapper(b, encoding='ascii', errors='surrogateescape')
63+
with pytest.raises(UnicodeEncodeError):
64+
pd.read_csv(t)
65+
5866
def test_delim_whitespace_custom_terminator(self):
5967
# See gh-12912
6068
data = """a b c~1 2 3~4 5 6~7 8 9"""

0 commit comments

Comments
 (0)