写入结构变量时发生strcpy访问冲突

strcpy access violation writing to a struct variable

本文关键字:strcpy 访问冲突 结构 变量      更新时间:2023-10-16

我有一个名为record的结构,它包含键、值对:

struct Record{
    char* key=new char();
    TYPE value=NULL;
    Record(){
        key = "default";
        value = 10;
    }
    Record(const char* key_, TYPE value_){
        strcpy(key, key_);
        value = value_;
    }
    const Record<TYPE>& operator=(const Record<TYPE>& other){
        key = other.key;
        value = other.value;
        return *this;
    }
};

此外,我有一个类"SimpleTable",它包含这些记录的数组:

class SimpleTable:public Table<TYPE>{
    struct Record<TYPE> *table;
public:

当我试图将日期放入这些记录时,问题就来了。我的strcpy给了我"访问违规写入位置"。(在类构造函数中初始化Records数组的所有元素):

template <class TYPE>
bool SimpleTable<TYPE>::update(const char* key, const TYPE& value){
    for (int i = 0; i < 10; i++){
        if (table[i].key == ""){
            strcpy(table[i].key , key); // <-------- crash right here
            table[i].value = value;
        }
    }
        return true;
}
char* key=new char();

只分配内存来容纳一个字符。

strcpy(table[i].key , key);

将导致未定义的行为,除非key是空字符串。

使用std::string key。如果不允许使用std::string,则必须重新访问代码并修复与key相关的内存问题。