C++ ~vector()在退出时导致SIGSEGV
这就是谷歌代码堵塞的商店信用问题。 我的代码在运行大型测试后发出一个SIGSEGV。但答案是正确的C++ ~vector()在退出时导致SIGSEGV,c++,valgrind,C++,Valgrind,这就是谷歌代码堵塞的商店信用问题。 我的代码在运行大型测试后发出一个SIGSEGV。但答案是正确的 #include <cstdio> #include <algorithm> #include <vector> using namespace std; int ps[1000]={0}; vector<int> indice[1000]; int main() { int cases; scanf("%d", &cases);
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
int ps[1000]={0};
vector<int> indice[1000];
int main() {
int cases; scanf("%d", &cases);
for(int j=1;j<=cases;j++) {
printf("Case #%d: ", j);
int c, is; scanf("%d%d", &c, &is);
for(int i=0;i<=c;i++) ps[i]=0;
for(int i=0;i<=c;i++) indice[i].clear();
for (int i = 0; i < is; i++) {
int it; scanf("%d", &it);
indice[it].push_back(i+1);
ps[it]=1;
if (c-it>0&&ps[c-it]) {
int a, b;
a = indice[it][0];
b = indice[c-it][0];
if(c==2*it&&indice[it].size()>1) {
b=indice[it][1];
}
if (a!=b) {
printf("%d %d\n", min(a,b),max(a,b));
}
}
}
}
return 0;
}
#包括
#包括
#包括
使用名称空间std;
int-ps[1000]={0};
向量指数[1000];
int main(){
int cases;scanf(“%d”和cases);
对于(intj=1;j,正如我所理解的valgrind,它无法检测到您写入的数组超出了静态分配的数组的边界。因此,让我们在堆上分配它们
vector<int> *indice = new vector<int>[1000];
int *ps = new int[1000];
使用gdb,我可以看到当您访问indice[1433]
时会出现SIGSEGV,这超出了indice
的范围
我还认为您的实际问题是,对于大型数据集,变量边界如下所示:
N = 50
3 ≤ I ≤ 2000
你确定不应该分配2001个元素而不是1000个元素吗?你能用向量的向量代替1000个硬编码向量吗。向量;哦,是的!非常感谢!我太粗心了。
==7168== Invalid read of size 8
==7168== at 0x4008D6: main (stl_vector.h:735)
==7168== Address 0x4c39e10 is 8 bytes after a block of size 24,008 alloc'd
==7168== at 0x4A07152: operator new[](unsigned long) (vg_replace_malloc.c:363)
==7168== by 0x400791: global constructors keyed to indice (foo.cc:6)
==7168== by 0x400C35: ??? (in /tmp/foo)
==7168== by 0x4005F2: ??? (in /tmp/foo)
==7168==
==7168== Invalid read of size 8
==7168== at 0x4008DA: main (stl_vector.h:735)
==7168== Address 0x4c39e18 is 16 bytes after a block of size 24,008 alloc'd
==7168== at 0x4A07152: operator new[](unsigned long) (vg_replace_malloc.c:363)
==7168== by 0x400791: global constructors keyed to indice (foo.cc:6)
==7168== by 0x400C35: ??? (in /tmp/foo)
==7168== by 0x4005F2: ??? (in /tmp/foo)
==7168==
N = 50
3 ≤ I ≤ 2000