2015-07-10 42 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