0

i'm trying to do insertion sort over vectors in C++ but my ./a.out returns this: * Error in `./insertion': double free or corruption (out): 0x000000000154fc20 *

Don't know why is this happenning, i've seen other problems like this and it's always about the code, buy in my code i don't know what the problem is.

This is the code:

#include<iostream>
#include<vector>

using namespace std;


void insertion(vector<int> v){
  int tam = v.size();
  int key,j,i;
  for(i=1; i<tam; i++){
    key = v[i];
    j=i-1;
    while(j>=0 && v[j]>key){
      v[j+1] = v[j];
      j--;
    }
    v[j]=key;
  }
}

void print(vector<int> v){
  cout<<endl;
  for(int i = 0; i<v.size(); i++){
    cout<<i+1<<".\t"<<v[i]<<"\n";
  }
}

int main(){
  cout<<"----------------INSERTION SORT----------------\n\n";
  cout<<"\nPlease, fill the vector: \n\n";
  vector<int> v;
  int a;
  bool response = true;

  while(response){
      cout<<"\nEnter your number: ";
      cin>>a;
      v.push_back(a);
      cout<<"Another?(1/0): ";
      cin>>response;
      cout<<endl;
  }
  insertion(v);
  print(v);

  return 0;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294

2 Answers2

0

In this snippet of your code, in insertion(),

j=i-1;
while(j>=0 && v[j]>key){
  v[j+1] = v[j];
  j--;
}
v[j]=key;

By definition, the while loop will terminate when j<0 or v[j]>key. When it terminates because j<0, assigning v[j]=key corrupts memory, since it is essentially v[-1]=key.

Matt Jordan
  • 2,133
  • 9
  • 10
-1

You have two options to fix that code:

1)

j=i-1;
    while(j>=0 && v[j]>key){
      v[j+1] = v[j];
      j--;
    v[j]=key;
    }

2)

j=i-1;
    while(j>=0 && v[j]>key){
      v[j+1] = v[j];
      j--;
    }
    v[j+1]=key;
Rafał
  • 19
  • 5
  • I didn't notice that, also it's very strange to me that type of notification about an error, btw i'm starting to program C++ in the terminal of Ubuntu, maybe that's why i didn't understand that. Thanks a lot :D –  Mar 30 '16 at 05:26