问题描述
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec;
for (int i = 0; i < 42; ++i) {
vec.push_back(i);
vec.push_back(-i);
}
for (int x: vec) {
for (int y: vec) {
vec.push_back(x + y);
}
}
for (int x: vec) {
std::cout << x << "\n";
}
}
是什么导致此代码崩溃?我尝试用-fsanitize = address进行编译,得到 == 9347 == ERROR:AddressSanitizer:地址0x61500000fdb4在pc 0x00010a4f1043 bp上的free-after-free堆使用0x7fff55710b70 sp 0x7fff55710b68
。当我的计算机上x == 0且y == 22时,它在 vec.push_back(x + y)
失败。
What's causing this code to crash? I tried compiling it with -fsanitize=address, got ==9347==ERROR: AddressSanitizer: heap-use-after-free on address 0x61500000fdb4 at pc 0x00010a4f1043 bp 0x7fff55710b70 sp 0x7fff55710b68
. It fails at vec.push_back(x + y)
when x == 0 and y == 22 on my computer.
推荐答案
来自:
基于范围的for循环在内部使用迭代器。使用 push_back
可能会使这些迭代器无效。
Range-based for loop uses iterators internally. Using push_back
may cause these iterators to be invalidated.
编辑:请注意,当 y == 22
您将第65个元素插入向量中。容量可能为64。许多实现将容量提高2的幂(每次加倍)。
Edit : Notice that when y == 22
you are inserting a 65th element into your vector. It's likely the capacity was 64. Many implementations increase capacity by powers of 2 (doubling it each time).
这篇关于基于范围的for循环和std :: vector.push_back()使程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!