IIUC, calling XrmSetDatabase(display, database) means the `database' is owned by the caller and it's responsible for freeing the newly associated database when it becomes no longer necessary.
Then, I think XrmSetDatabase should reset the XlibDisplayDfltRMDB flag even if display->db is previously set to NULL so it may not be destroyed by the next XrmSetDatabase or XCloseDisplay call.
A concrete problem in an application can be found at http://lists.gnu.org/archive/html/bug-gnu-emacs/2009-05/msg00633.html .
Mass closure: This bug has been untouched for more than six years, and is not
obviously still valid. Please reopen this bug or file a new report if you continue to experience issues with current releases.