2015-07-10 48 views
1

我試圖創建一個函數來獲得使用在C try和catch方法++用戶名。不幸的是,這段代碼不起作用,並且我的應用程序在嘗試運行時關閉。創建一個函數來獲取使用try和catch方法的用戶名在C++

QString UserInfo::getFullUserName() 
{ 
    DBG_ENTERFUNC(getFullUserName); 
    QString result; 
    qDebug("trying to get the username"); 
    try 
{ 
    struct passwd fullUserData=*getpwnam(getUserName().toLatin1()); 
    result = fullUserData.pw_gecos; 
    // it is the first of the comma seperated records that contain the user name 
    result = result.split(",").first(); 
    if (result.isEmpty()) 
    { 
    result = getUserName(); 
    } 
} 
catch (...) 
{ 
    qDebug("exception caught"); 
} 
qDebug() << result; 

#endif 

    DBG_EXITFUNC; 
    return result; 
} 

問題發生在這行代碼中,因爲我已將打印後的打印文件放在打印機後面,永遠不會到達。

struct passwd fullUserData=*getpwnam(getUserName().toLatin1()); 

有沒有人知道這裏有什麼問題?

*編輯--------

這裏是我的功能getUserName()

QString UserInfo::GetUserName() 
{ 
    DBG_ENTERFUNC(GetUserName); 
    QString result; 
    foreach (QString environmentEntry, QProcess::systemEnvironment()) 
    { 
    QString varName = environmentEntry.section('=',0,0); 
    QString varValue = environmentEntry.section('=',1,1); 

    if (varName == "USER" || varName == "USERNAME") 
    { 
     result = varValue; 
    } 
    } 
    DBG_EXITFUNC; 
    return result; 
} 
+0

您是否有任何異常消息? –

+2

如果找不到名稱(或發生其他錯誤),getpwnam將返回一個空指針。在嘗試解除引用之前,您需要檢查它。 – Mat

回答

4

getpwnam()回報NULL時未找到的用戶名。您可能取消引用NULL指針。

*getpwnam(getUserName().toLatin1()); 
//^potential NULL pointer deref 

deferencing潛在無效指針之前,請務必檢查:

struct passwd *fullUserData = getpwnam(getUserName().toLatin1()); 
//   ^note pointer 
if (fullUserData != NULL) { 
    result = fullUserData->pw_gecos; 
    //     ^^ fullUserData is a struct pointer 
} else { 
    // throw Exception 
} 

如果這讓你,你可能會想在C++和指針讀了。

+0

當我這樣做時,我得到以下錯誤。 「錯誤:不對應的‘!運算符=’(操作數類型是‘passwd文件’和‘INT’) 如果(fullUserData!= NULL)」 – Hilary

+0

再次檢查,我也* *變化的變量聲明爲指針。 – dhke

+0

哦,我明白了。我沒有仔細閱讀。我已經改變了我的代碼,使一個NULL返回的檢查和事實證明,getpwnam是返回NULL,所以我的錯誤一定要在其他地方 – Hilary