Issue #4046: Backport of issue #3312's patch: fixes two crashes in the sqlite3
module.
diff --git a/Misc/NEWS b/Misc/NEWS
index dde30ae..a492d46 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -215,6 +215,9 @@
 - Issue #1471: Arguments to fcntl.ioctl are no longer broken on 64-bit OpenBSD
   and similar platforms due to sign extension.
 
+- Issue #3312: Fix two crashes in sqlite3.
+
+
 Tests
 -----
 
diff --git a/Modules/_sqlite/connection.c b/Modules/_sqlite/connection.c
index 703af15..d491688 100644
--- a/Modules/_sqlite/connection.c
+++ b/Modules/_sqlite/connection.c
@@ -822,6 +822,7 @@
 {
     PyObject* res;
     PyObject* begin_statement;
+    char* begin_statement_str;
 
     Py_XDECREF(self->isolation_level);
 
@@ -854,12 +855,18 @@
             return -1;
         }
 
-        self->begin_statement = PyMem_Malloc(PyString_Size(begin_statement) + 2);
+        begin_statement_str = PyString_AsString(begin_statement);
+        if (!begin_statement_str) {
+            Py_DECREF(begin_statement);
+            return -1;
+        }
+        self->begin_statement = PyMem_Malloc(strlen(begin_statement_str) + 2);
         if (!self->begin_statement) {
+            Py_DECREF(begin_statement);
             return -1;
         }
 
-        strcpy(self->begin_statement, PyString_AsString(begin_statement));
+        strcpy(self->begin_statement, begin_statement_str);
         Py_DECREF(begin_statement);
     }
 
diff --git a/Modules/_sqlite/module.c b/Modules/_sqlite/module.c
index 606454c..bfaf730 100644
--- a/Modules/_sqlite/module.c
+++ b/Modules/_sqlite/module.c
@@ -128,12 +128,15 @@
 {
     PyTypeObject* type;
     PyObject* caster;
+    int rc;
 
     if (!PyArg_ParseTuple(args, "OO", &type, &caster)) {
         return NULL;
     }
 
-    microprotocols_add(type, (PyObject*)&SQLitePrepareProtocolType, caster);
+    rc = microprotocols_add(type, (PyObject*)&SQLitePrepareProtocolType, caster);
+    if (rc == -1)
+        return NULL;
 
     Py_INCREF(Py_None);
     return Py_None;