是否赋值代码会导致崩溃

Does the assignment code will lead to crash?

本文关键字:崩溃 赋值 代码 是否      更新时间:2023-10-16
class SMTkrSym {
  enum { SMTKRLEN = 16 };
  uint8     data[SMTKRLEN];
 public:
  SMTkrSym() { memset(&data, 0, sizeof data); }
  SMTkrSym(const char* pIn) { if (Read(pIn) < 0) memset(&data, 0, sizeof data); }
  int16 Show(char* outstr) const; // display ticker symbol
  int16 Read(const char* instr); // read ticker symbol
  bool operator==(const SMTkrSym& rhs) const { return strncmp((char*)data, (char*)rhs.data, SMTKRLEN) == 0; }
  bool operator!=(const SMTkrSym& rhs) const { return !(*this == rhs); }
  bool operator>(const SMTkrSym& rhs) const { return (strncmp((char*)data, (char*)rhs.data, SMTKRLEN) > 0); }
  bool operator<=(const SMTkrSym& rhs) const { return !(*this > rhs); }
  bool operator<(const SMTkrSym& rhs) const { return (strncmp((char*)data, (char*)rhs.data, SMTKRLEN) < 0); }
  bool operator>=(const SMTkrSym& rhs) const { return !(*this < rhs); }
};
unsigned int SMTkrSym::Read(const char* instr)
{
 unsigned int i,j;
 for (i = 0; (i < SMTKRLEN) && *instr; i++)  // display until null
   data[i] = *instr++;
 for (j = i; j < SMTKRLEN; j++)
   data[j] = '';      // null out rest of symbol
 return i;     // return actual number of characters
}

这个类的用法如下:

char pData[] = "helloworldyyyyyy";
char* p = pData;
SMTkrSym key1(p);
SMTkrSym key2;
key2 = key1;

pData的长度等于16。

SMTkrSym复制构造函数将调用read函数,并且当instr的长度大于或等于16时,它不会放置''结束符。

我的问题是当程序运行key2 = key1,它会导致崩溃吗?

当运行key2 = key1时,它将调用默认赋值操作符函数。

但是key1的数据成员变量不包含结束符。

我担心的是如果默认赋值函数使用strcpy函数

复制数据成员变量,可能导致内存溢出。

我想如果赋值函数看起来像memcpy(&key2, &key1,Sizeof (key1)),它不会崩溃。默认赋值是如何工作的?

默认编译器提供的operator=不会使用strcpy()复制data[]…它将安全地复制数组中的所有字符,就像您所说的通过memcpy一样,尽管它实际上可能不使用memcpy