Issue #3313: Contrary to the man page, a failed dlopen() call does not
always set a dlerror() message.
diff --git a/Misc/NEWS b/Misc/NEWS
index 8562176..d39bc59 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -57,6 +57,9 @@
 Library
 -------
 
+- Issue #3313: Fixed a crash when a failed dlopen() call does not set
+  a valid dlerror() message.
+
 - Issue #3258: Fixed a crash when a ctypes POINTER type to an
   incomplete structure was created.
 
diff --git a/Modules/_ctypes/callproc.c b/Modules/_ctypes/callproc.c
index b16d7b0..01ba8a0 100644
--- a/Modules/_ctypes/callproc.c
+++ b/Modules/_ctypes/callproc.c
@@ -1410,8 +1410,11 @@
 	mode |= RTLD_NOW;
 	handle = ctypes_dlopen(name, mode);
 	if (!handle) {
+		char *errmsg = ctypes_dlerror();
+		if (!errmsg)
+			errmsg = "dlopen() error";
 		PyErr_SetString(PyExc_OSError,
-				       ctypes_dlerror());
+				       errmsg);
 		return NULL;
 	}
 	return PyLong_FromVoidPtr(handle);
diff --git a/Modules/dlmodule.c b/Modules/dlmodule.c
index ccf1cb1..b2ea4f5 100644
--- a/Modules/dlmodule.c
+++ b/Modules/dlmodule.c
@@ -186,7 +186,10 @@
 	}
 	handle = dlopen(name, mode);
 	if (handle == NULL) {
-		PyErr_SetString(Dlerror, dlerror());
+		char *errmsg = dlerror();
+		if (!errmsg)
+			errmsg = "dlopen() error";
+		PyErr_SetString(Dlerror, errmsg);
 		return NULL;
 	}
 #ifdef __VMS