在c++中使用try和catch方法创建一个函数来获取用户名

Create a function to get a username using a try and catch method in C++

本文关键字:一个 函数 用户 获取 创建 c++ try 方法 catch      更新时间:2023-10-16

我试图创建一个函数,以获得一个用户名使用尝试和捕获方法在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;
}

getpwnam()在未找到用户名时返回NULL。您可能正在解引用NULL指针。

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

总是在放弃一个可能无效的指针之前检查:

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

如果这让你感到困惑,你可能需要阅读c++和指针。