Zachary Rudebeck
Zachary Rudebeck

Reputation: 63

c++ Segmentation Fault using struct pointer

I have a class called Dictionary that contains a key-value pair, a pointer to this key-value pair, and an int that holds the size of the dictionary.

template<typename K, typename V>
class Dictionary
{
public:

V& operator[](K key);

private:

struct KeyValue
{
    K key;
    V value;
}; //the key-value pair struct

KeyValue* array; //pointer to an array of items (the key-value pairs)

int size; //size of the dictionary (i.e. the array size)
};

I am trying to overload the [] operator for this class and when I do so, I get a segmentation fault error

template<typename K, typename V>
V& Dictionary<K,V>::operator[](K key){
  for (size_t i = 0; i < size; i++) {
    if (key == array[i].key) {
      return array[i].value;
    }
  }
  array[size].value = 0;
  size++;
  return array[size-1].value;
}

I beleive that the seg fault is occuring in this line

array[size].value = 0;

However, I don't know exactly why it's happening. Any help is greatly appreciated. Thanks!

Upvotes: 1

Views: 224

Answers (1)

NicholasM
NicholasM

Reputation: 4673

When an array in C and C++ has N elements, the valid indexes are: 0, 1, 2, ... N-1. In contrast N is not a valid index: it is past the end of the array.

In this particular case, the last element of array is array[size - 1]:

array[0]         // first element
array[1]         // second element
// ...
array[size - 2]  // second-to-last element
array[size - 1]  // last element

array[size]      // error: beyond the last element

Using array[size] is accessing beyond the end of the array and results in a segmentation fault.

In the bigger picture, if you need to add elements to an array and you are out of space in the array, you would need to allocate a new array with larger size, and move (or copy) elements from the old array to the new array.

This is "reallocating", and this is what std::vector<T> does when it grows beyond its current capacity.

You may want to replace your use of a dynamic array with an std::vector<KeyValue>. That would let the std::vector take care of these operations.

Upvotes: 5

Related Questions