我想用 qtcreator 在 Windows 上测试计数排序。我为 countsort 编写了一个函数,它返回 vector
堆[labhw1.exe]:
Heap block at 0000000000995120 modified at 00000000009960D0 past requested size of fa0.
调试显示 ~vector 出错了。如果我想为 B 分配新值,它也会中断。 operator= 将调用 ~vector。似乎无法正确释放 B。
readtxt 是一个从 txt 文件中读取整数并返回 vector 的函数。我认为它只是一个 int vector ,所以与指针无关。也许这是生命范围造成的。谁能告诉我为什么?
调试显示:
1 ntdll!RtlpNtSetValueKey 0x7ff9a61515f3
2 ntdll!RtlZeroHeap 0x7ff9a613f555
3 ntdll!memset 0x7ff9a610e9af
4 ntdll!RtlpNtSetValueKey 0x7ff9a61504b1
5 ntdll!RtlReAllocateHeap 0x7ff9a605e57b
6 ntdll!RtlFreeHeap 0x7ff9a606061c
7 msvcrt!free 0x7ff9a37298bc
8 __gnu_cxx::new_allocator<int>::deallocate new_allocator.h 125 0x403990
9 std::allocator_traits<std::allocator<int>>::deallocate alloc_traits.h 462 0x40442b
10 std::_Vector_base<int, std::allocator<int>>::_M_deallocate stl_vector.h 180 0x404252
11 std::_Vector_base<int, std::allocator<int>>::~_Vector_base stl_vector.h 162 0x4043c1
12 std::vector<int>::~vector stl_vector.h 435 0x404c11
13 main main.cpp 19* 0x4020b4
*行:vector
vector<int> countsort(vector<int> A){
int k=0;
for (auto a:A){
if(a>k)k=a;
}
vector<int> C(k+1,0);
for (int i=0;i<A.size();i++)C[A[i]]+=1;
for (int i=1;i<k+1;i++)C[i]=C[i-1]+C[i];
vector<int> B(A.size(),0);
for(int j=A.size()-1;j>=0;j--){
B[C[A[j]]]=A[j];
C[A[j]]-=1;
}
return B;
}
int main(){
vector<int> A=readtxt("A.txt");
vector<int> B;
B = countsort(A);
return 0;
}
最佳答案
一个提示,当你使用 vector 并且你的程序崩溃时调用 vector 上的 at
方法而不是 []
因为 at
抛出异常 - 它是有用的信息。你的程序在这一行崩溃
B[C[A[j]]]=A[j];
改成
B.at( C[A[j]] ) = A[j];
你会得到异常 - 超出范围。 B
vector 太小。 B
的大小应该是
max-value-of-C + 1
所以构造B vector 如下
vector<int> B( *max_element(C.begin(),C.end()) + 1 ,0 );
现在可以了。
关于c++ - 函数分配的 vector<int> 未正确释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52440370/