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

239 Views Asked by At

I'm trying to create a function to get a username using a try and catch method in C++. Unfortunately this code doesn't work, and my application closes when it tries to run.

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;
}

The problem occurs in this line of code as I have placed prints after it that are never reached.

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

Does anyone know what is the issue here?

*Edit--------

Here is my function 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;
}
1

There are 1 best solutions below

5
On

getpwnam() returns NULL when the username was not found. You are potentially dereferencing a NULL pointer.

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

Always check before deferencing a potentially invalid pointer:

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

If this is confusing to you, you might want to read up on C++ and pointers.