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


i'm trying create function username using try , catch method in c++. unfortunately code doesn't work, , application closes when tries run.

qstring userinfo::getfullusername() {   dbg_enterfunc(getfullusername);   qstring result;   qdebug("trying username");   try {   struct passwd fulluserdata=*getpwnam(getusername().tolatin1());   result = fulluserdata.pw_gecos;   // first of comma seperated records contain 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 line of code have placed prints after never reached.

struct passwd fulluserdata=*getpwnam(getusername().tolatin1()); 

does know issue here?

*edit--------

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

getpwnam() returns null when username not found. potentially dereferencing null pointer.

   *getpwnam(getusername().tolatin1()); // ^ potential null pointer deref 

always check before deferencing potentially invalid pointer:

struct passwd *fulluserdata = getpwnam(getusername().tolatin1()); //            ^ note pointer if (fulluserdata != null) {     result = fulluserdata->pw_gecos;     //                   ^^ fulluserdata struct pointer } else {      // throw exception } 

if confusing you, might want read on c++ , pointers.


Comments