1

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 Answers1

4

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.

dhke
  • 15,008
  • 2
  • 39
  • 56
  • When I do this I get the following error. 'error: no match for ‘operator!=’ (operand types are ‘passwd’ and ‘int’) if (fullUserData !=NULL)' –  Jul 10 '15 at 11:59
  • Check again, I've *also* changed the variable declaration to a pointer. – dhke Jul 10 '15 at 12:02
  • Oh I see. I hadn't read it closely enough. I have changed my code to include a check for a NULL return and as it turns out, getpwnam is returning NULL, so my error must be elsewhere –  Jul 10 '15 at 12:29
  • getUserName returns a string of characters. I believe the error might be my use of pointers to the string? I have attached the code for the getUserName function above in my question. –  Jul 10 '15 at 13:33
  • I'm not too familiar with QT, but as far as I know, `toLatin1()` returns a `QByteArray` which converts to the required `const char *` of `getpwnam()`, so the memory management is handled for you. – dhke Jul 10 '15 at 13:38