堆栈分配结构总是在同一位置
Stack allocated struct always in the same location?
我正在为哈希表编写插入函数,我需要在该函数中创建一个键值对(struct Item)。我发现,如果我在堆栈上创建它,例如Item item(key, value);
,那么每次当我调用Insert时,不同的键值对将在堆栈上的相同位置创建。如果我使用堆分配内存,就不会发生这种情况。为什么它们在堆栈上的位置相同?
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是堆栈分配的,我使用它的方式在注释中。
堆栈分配的版本不起作用,因为您存储的是指向局部变量的指针,该指针稍后会超出作用域。
相关文章:
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 是否可以将值分配给移出位置?
- 创建一个类来访问和指定向量类型,并构建一个获取位置并为其分配区域的类
- 在尝试使用CUDA分配内存时,我遇到了访问冲突写入位置错误
- 为什么动态分配的两个变量的内存位置不是连续的?
- 为字符串中的每个字符(不是字符位置!)分配唯一的索引
- 只读位置'__result.std::_Rb_tree_const_iterator<_Tp>::operator*<long long int>()'分配错误
- 每次我分配新的位置时,都会隐式地称为destuructor
- 在动态分配矩阵上的访问违规读数位置
- 如何专用/分配自定义内存位置,以便可以在C 中编辑该位置
- C 中的内存模型:为什么在同一内存位置分配了结构中的两个整数
- 动态分配存储数据在堆中的随机位置中
- 在为矩阵分配值时访问冲突写入位置0x00000000
- 分配浮点时访问违规位置(0x0000000000000170)
- 为什么在C 中的堆中的垃圾位置无法重新分配
- 使用set_union合并两组时,只读位置的分配
- 明确分配或从内存中的特定地址/位置分配或访问值
- 在特定位置分配多态类成员
- 有没有一种方法可以从特定的内存位置分配内存
- g++ 4.9.0允许对位置分配使用operator delete[](void*, size_t)