Index: Lib/test/pickletester.py =================================================================== --- Lib/test/pickletester.py (revision 66951) +++ Lib/test/pickletester.py (working copy) @@ -996,6 +996,20 @@ pickle.Pickler(f, -1) pickle.Pickler(f, protocol=-1) + def test_bad_init(self): + # Test issue3664 (pickle can segfault from a badly initialized Pickler). + from io import BytesIO + # Override initialization without calling __init__() of the superclass. + class BadPickler(pickle.Pickler): + def __init__(self): pass + + class BadUnpickler(pickle.Unpickler): + def __init__(self): pass + + self.assertRaises(pickle.PicklingError, BadPickler().dump, 0) + self.assertRaises(pickle.UnpicklingError, BadUnpickler().load) + + class AbstractPersistentPicklerTests(unittest.TestCase): # This class defines persistent_id() and persistent_load() Index: Modules/_pickle.c =================================================================== --- Modules/_pickle.c (revision 66951) +++ Modules/_pickle.c (working copy) @@ -421,6 +421,11 @@ { PyObject *data, *result; + if (self->write_buf == NULL) { + PyErr_SetString(PyExc_SystemError, "invalid write buffer"); + return -1; + } + if (s == NULL) { if (!(self->buf_size)) return 0; @@ -2378,6 +2383,16 @@ { PyObject *obj; + /* Check whether the Pickler was initialized correctly (issue3664). + Developers often forget to call __init__() in their subclasses, which + would trigger a segfault without this check. */ + if (self->write == NULL) { + PyErr_Format(PicklingError, + "Pickler.__init__() was not called by %s.__init__()", + Py_TYPE(self)->tp_name); + return NULL; + } + if (!PyArg_ParseTuple(args, "O:dump", &obj)) return NULL;