c++ - 函数分配的 vector<int> 未正确释放

标签 c++ c++11 vector

我想用 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 B

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/

相关文章:

c++ - C++11标准中实例化单元的含义是什么?

c++ - 袖口 : How to calculate the fft when the input is a pitched array

c++ - std::move() 的错误用法?

c++ - 是否有任何 C++ 静态分析工具来检测 vector 的潜在错误

matlab - 如何在 MatLab 中按元素组合两个大小相等的向量?

重复向量以填充数据框中的列

c++ - 使类不可复制*和*不可 move

c++ - 从 WebView QML 元素访问 QWebPage 对象

c++ - 访问私有(private)嵌套类

c++11 - 如何使用 Eigen 的逐元素整数幂