diff --git a/modules/access/sftp.c b/modules/access/sftp.c
index 1c05500c0017f7cc2fbce84a2e3d2bdadbece3c7..36af38f09f557011dd3e5e56b6f0048db75cdfc4 100644
--- a/modules/access/sftp.c
+++ b/modules/access/sftp.c
@@ -324,13 +324,17 @@ static int Open( vlc_object_t* p_this )
         goto error;
 
     psz_home = config_GetUserDir( VLC_HOME_DIR );
-    char *psz_knownhosts_file;
-    if( asprintf( &psz_knownhosts_file, "%s/.ssh/known_hosts", psz_home ) != -1 )
+    if (likely(psz_home != NULL))
     {
-        if( libssh2_knownhost_readfile( ssh_knownhosts, psz_knownhosts_file,
-                                        LIBSSH2_KNOWNHOST_FILE_OPENSSH ) < 0 )
-            msg_Err( p_access, "Failure reading known_hosts '%s'", psz_knownhosts_file );
-        free( psz_knownhosts_file );
+        char *psz_knownhosts_file;
+        if( asprintf( &psz_knownhosts_file, "%s/.ssh/known_hosts", psz_home ) != -1 )
+        {
+            if( libssh2_knownhost_readfile( ssh_knownhosts, psz_knownhosts_file,
+                                            LIBSSH2_KNOWNHOST_FILE_OPENSSH ) < 0 )
+                msg_Err( p_access, "Failure reading known_hosts '%s'", psz_knownhosts_file );
+            free( psz_knownhosts_file );
+        }
+        free( psz_home );
     }
 
     const char *fingerprint = libssh2_session_hostkey( p_sys->ssh_session, &i_len, &i_type );
@@ -558,7 +562,6 @@ static int Open( vlc_object_t* p_this )
     i_result = VLC_SUCCESS;
 
 error:
-    free( psz_home );
     free( psz_session_username );
     free( psz_path );
     vlc_credential_clean( &credential );