vendredi 21 septembre 2018

vector

I want to test counting sort on windows with qtcreator. I write a function for countsort which returns vector< int >. For the code below, after it is executed it will show

HEAP[labhw1.exe]: Heap block at 0000000000995120 modified at 00000000009960D0 past requested size of fa0.

The debug shows ~vector went wrong. If I want to assign new value to B, it will also break. The operator= will invoke ~vector. It seems that B can not be correctly deallocated.

readtxt is a function that read integers from a txt file and return a vector. I think it's just a vector of int so there is nothing to do with pointers. Maybe this is caused by the life scope. Could anyone tell me why? The debug shows :

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::deallocate new_allocator.h 125 0x403990
9 std::allocator_traits>::deallocate alloc_traits.h 462 0x40442b
10 std::_Vector_base>::_M_deallocate stl_vector.h 180 0x404252
11 std::_Vector_base>::~_Vector_base stl_vector.h 162 0x4043c1
12 std::vector::~vector stl_vector.h 435 0x404c11
13 main main.cpp 19* 0x4020b4

*the line: vector< int > 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;
}

Aucun commentaire:

Enregistrer un commentaire