【问题标题】:strcpy access violation writing to a struct variablestrcpy 访问冲突写入结构变量
【发布时间】:2015-03-26 21:03:01
【问题描述】:

我有一个名为 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(); 分配一个字符。 char* key=new char[10]; 在那里根据需要分配一个数组。赋值运算符中的key = other.key; 也是错误的。
  • 您分配了一个字符,然后继续在其上复制整个字符串,您期望什么?
  • 请不要大写实际上是小写的 C 标识符(在我编辑之前,您的标题有 Strcpy 而不是 strcpy)。很容易有另一个函数叫做Strcpy。

标签: c++ arrays string struct strcpy


【解决方案1】:
char* key=new char();

只分配内存来保存一个字符。

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

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

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

【讨论】:

  • 另外,key = "default"; 会丢弃指向您分配的字符的指针,并将其替换为指向常量的指针。你不能修改常量,所以现在key 指向你不能修改的东西。所以试图复制到它会失败。 (要将某些内容复制到指针指向的内容中,指针必须指向您可以修改的内容。)
猜你喜欢
  • 1970-01-01
  • 2019-10-24
  • 2010-11-19
  • 1970-01-01
  • 2022-12-20
  • 2021-12-11
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
相关资源
最近更新 更多