-1

I am writing an Insert function for a hash table and I need to create a key-value pair(struct Item) in that function. I found that if I create it on the stack e.g. Item item(key, value);, then every time when I call Insert, different key-value pair will be created in the same location on the stack. This won't happen if I use heap-allocation memory. Why they are at the same location on the stack?

Here is my sample code:

void Insert (int key, int value) {
int hash_value = Hash(key);
if (hash_value >= table.size() || hash_value < 0) {
  throw std::out_of_range("Cannot insert.");      
} else {
  Item *item = new Item(key, value);  // This will work
  // Item item2(key, value); This does not work
  if (!table[hash_value]) {  // there is not item in this cell
    Cell *c = new Cell(0, item);  // Cell *c = new Cell(0, &item2)
    table[hash_value] = c;
  } else {  // try next one, if occupied, the one after ...
    int index = hash_value + 1;
    while (table[index]) {
      ++index;
      if (index == table.size()) {
        index = 0;
      } else if (index == hash_value) {
        throw std::out_of_range("Opps! The table is full! Cannot insert!");
      }
    }
    Cell *c = new Cell(0, item);  // Cell *c = new Cell(0, &item2)
    table[index] = c;
  }
}

}

Item2 is stack allocated and the way I used it was in the comments.

ZigZagZebra
  • 1,349
  • 3
  • 14
  • 25
  • 1
    Please reduce code before asking here, this has nothing to do with hash tables, for example. You should also use C++'s containers (`std::unordered_map` probably) instead. – Ulrich Eckhardt Sep 26 '15 at 14:05

1 Answers1

2

The stack-allocated version doesn't work because you are storing a pointer to a local variable, which later goes out of scope. You retain the pointer beyond the lifetime of the object itself.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436