jeudi 22 août 2019

Code crashes. While pass c char array to function which catch with std::string

Code crashes While pass c char array (i.e data_info.user_name in my case) to function which catch with std::string.

Core get generated when calling SendClient(). I suspect this is because of the data being passed i.e data_info.user_name (char array) not sure about the root cause. Can anyone please point at the error.

void DataProcessingImpl::onUpdate(const DB_DATA_INFO& data_info) {
  std::vector<DataProcessingImpl*>::iterator iter = observer.begin();
  for (; iter != observer.end(); ++iter)
    (*iter)->SendClient(data_info.user_name); // This line core is generated
  }

GDB BT :

0x0000001254dergfd in void std::__1::__invoke_void_return_wrapper<void>::__call<std::__1::__bind<void (UserInfo::DataProvider::*)(DB_DATA const&), UserInfo::DataProvider*, std::__1::placeholders::__ph<1>&>&, DB_DATA const&>(std::__1::__bind<void (UserInfo::DataProvider::*)(DB_DATA const&), UserInfo::DataProvider*, std::__1::placeholders::__ph<1>&>&, DB_DATA const&) () from

Definition of DB_DATA_INFO

#define LEN 25
typedef struct DB_DATA
{
    char user_name[24];

    DB_DATA() : user_name("") {}
    DB_DATA(const DB_DATA& value) : user_name("") {
        std::strncpy(user_name, value.user_name, LEN);
        }
    DB_DATA(const char* value) : user_name("")
    {
        if (value == nullptr)
        {
            std::memset(user_name, 0, sizeof user_name);
        }
        else
        {
            std::strncpy(user_name, value, LEN);
        }
    }
    DB_DATA(std::string value) : user_name("") {

        std::strncpy(user_name, value.c_str(), LEN);

    }

    DB_DATA& operator=(const DB_DATA &db_val)
    {
        std::strncpy(user_name, db_val.user_name, LEN);
        return *this;
    }

    bool operator==(const char* db_val)
    {
        bool ret = false;
        if (db_val == nullptr)
        {
            ret = (std::strlen(user_name) == 0);
        }
        else
        {
            ret = (std::strncmp(user_name, db_val, LEN) == 0);
        }
    bool operator!=(const char* db_val)
    {
        bool ret = false;
        if (db_val == nullptr)
        {
            ret = !(std::strlen(user_name) == 0);
        }
        else
        {
            ret = !(std::strncmp(user_name, db_val, LEN) == 0);
        }
        return ret;
    }
     bool operator==(const DB_DATA& db_val) {
         return (std::strncmp(user_name, db_val.user_name, LEN) == 0);
         }
     bool operator!=(const DB_DATA& db_val) {
          return !(std::strncmp(user_name, db_val.user_name, LEN) == 0);
          }
} DB_DATA_INFO;

Aucun commentaire:

Enregistrer un commentaire