diff --git a/apps/app_voicemail.c b/apps/app_voicemail.c
index a4deb9b9bc406bc1f66d01efc9ad31bc7c51600f..e80a6039881ac26dbc69a4614d0f3df1e6fac2ee 100644
--- a/apps/app_voicemail.c
+++ b/apps/app_voicemail.c
@@ -1577,17 +1577,21 @@ static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const cha
 	struct ast_vm_user *retval;
 
 	if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
-		if (!ivm)
-			ast_set_flag(retval, VM_ALLOCED);	
-		else
+		if (ivm) {
 			memset(retval, 0, sizeof(*retval));
-		if (mailbox) 
-			ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
+		}
 		populate_defaults(retval);
-		if (!context && ast_test_flag((&globalflags), VM_SEARCH))
+		if (!ivm) {
+			ast_set_flag(retval, VM_ALLOCED);
+		}
+		if (mailbox) {
+			ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
+		}
+		if (!context && ast_test_flag((&globalflags), VM_SEARCH)) {
 			var = ast_load_realtime("voicemail", "mailbox", mailbox, SENTINEL);
-		else
+		} else {
 			var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, SENTINEL);
+		}
 		if (var) {
 			apply_options_full(retval, var);
 			ast_variables_destroy(var);
@@ -2660,8 +2664,10 @@ static int inboxcount2(const char *mailbox_context, int *urgentmsgs, int *newmsg
 			return -1;
 		}
 		if ((*newmsgs = __messagecount(context, mailboxnc, vmu->imapfolder)) < 0) {
+			free_user(vmu);
 			return -1;
 		}
+		free_user(vmu);
 	}
 	if (oldmsgs) {
 		if ((*oldmsgs = __messagecount(context, mailboxnc, "Old")) < 0) {
@@ -2979,8 +2985,9 @@ static struct ast_vm_user *find_user_realtime_imapuser(const char *imapuser)
 	vmu = ast_calloc(1, sizeof *vmu);
 	if (!vmu)
 		return NULL;
-	ast_set_flag(vmu, VM_ALLOCED);
+
 	populate_defaults(vmu);
+	ast_set_flag(vmu, VM_ALLOCED);
 
 	var = ast_load_realtime("voicemail", "imapuser", imapuser, NULL);
 	if (var) {
@@ -11742,8 +11749,8 @@ AST_TEST_DEFINE(test_voicemail_vmuser)
 	if (!(vmu = ast_calloc(1, sizeof(*vmu)))) {
 		return AST_TEST_NOT_RUN;
 	}
-	ast_set_flag(vmu, VM_ALLOCED);
 	populate_defaults(vmu);
+	ast_set_flag(vmu, VM_ALLOCED);
 
 	apply_options(vmu, options_string);
 
@@ -11871,7 +11878,7 @@ AST_TEST_DEFINE(test_voicemail_vmuser)
 		res = 1;
 	}
 	if (strcasecmp(vmu->imapfolder, "INBOX")) {
-		ast_test_status_update(test, "Parse failure for imappasswd option\n");
+		ast_test_status_update(test, "Parse failure for imapfolder option\n");
 		res = 1;
 	}
 	if (strcasecmp(vmu->imapvmshareid, "6000")) {