-2

I have a struct called record which contains key, value pair:

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

Also, I have a class "SimpleTable" which contains an array of those records:

class SimpleTable:public Table<TYPE>{

    struct Record<TYPE> *table;

public:

Problem comes when I try to put date inside those records. My strcpy gives me "Access violation writing location". (All elements of Records array initialized in class constructor):

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;
}
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Yochert
  • 85
  • 9
  • `char* key=new char();` allocates a single char. `char* key=new char[10];` allocates an array as you need there. `key = other.key;` in the assignment operator is also wrong. – πάντα ῥεῖ Mar 26 '15 at 21:13
  • you allocate a single character then proceed to copy an entire string on top of it, what did you expect? – Captain Obvlious Mar 26 '15 at 21:23
  • Please don't capitalize C identifier that are actually in lower case (your title had `Strcpy` rather than `strcpy` before I edited it). There could easily be another function called `Strcpy`. – Keith Thompson Mar 26 '15 at 22:01

1 Answers1

1
char* key=new char();

only allocates memory to hold one character.

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

will lead to undefined behavior unless key is an empty string.

Use std::string key. If you are not allowed to use std::string, you'll have to revisit your code and fix memory issues related to key.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Also, `key = "default";` throws away the pointer to the character you allocated and replaces it with a pointer to a constant. You can't modify a constant, so now `key` points to something you can't modify. So trying to copy into it will fail. (To copy something into what a pointer points to, the pointer must point to something you can modify.) – David Schwartz Mar 26 '15 at 22:02