c++dynamic-programmingcoredumpedit-distance

Random error core dump :Error in `./a.out': free(): invalid next size (fast): 0x00000000010e8d70 *** Aborted (core dumped)


#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using std::string;

int edit_distance(const string &str1, const string &str2) {
  std::vector<std::vector<int>> strMat(str1.length()+1,std::vector<int>(str2.length(),0));
  
  for(int i=0;i<=str1.length();i++){
    strMat[i][0] = i;
  }
  for(int j=0;j<=str2.length();j++){
    strMat[0][j] = j;
  }
    
  for(int i=1;i<=str1.length();i++){
      for(int j=1;j<=str2.length();j++){
              int min1 = std::min(strMat[i][j-1]+1,strMat[i-1][j]+1);
              int min2;
       
              if(str1[i-1]==str2[j-1]){
                  min2 = std::min(min1,strMat[i-1][j-1]);
              }
              else if(str1[i-1]!=str2[j-1]){
                  min2 = std::min(min1,strMat[i-1][j-1]+1);
              }
              strMat[i][j] = min2;
          }
      }
  
  int ans = strMat[str1.length()][str2.length()]; 
  return ans;
}

int main() {
  string str1;
  string str2;
  std::cin >> str1 >> str2;
  
  std::cout << edit_distance(str1, str2) << std::endl;
  return 0;
}

I am getting error :"***** Error in `./a.out': free(): invalid next size (fast): 0x00000000010e8d70 *** Aborted (core dumped)**" randomly at random inputs. Many times it works on same input and some times it fails and gives that error.

It is giving correct output on cases where it does not throws error.


Solution

  • What happens is that you are going out of bounds when writing to the vector.

    You shouldn't use C style [] to access the array instead you should use .at(index) because it does bounds checking.

      std::vector<std::vector<int>> strMat(str1.length()+1,std::vector<int>(str2.length(),0));
    

    The inner vector is of size str2.length()

    Here you are writing to 1 element past its size.

     for(int j=0;j<=str2.length();j++){
        strMat[0][j] = j;
    
    

    You have the same issue here:

      for(int i=1;i<=str1.length();i++){
          for(int j=1;j<=str2.length();j++){ // j <= str2.length() will cause you to access elements in the vector that are outside of its bounds
    

    Also here:

      int ans = strMat[str1.length()][str2.length()]; 
    

    Since indexing in c++ is 0 based, when you instantiate the vector to have space for str2.length() elements, the index of the last element will be at str2.length() -1

    You can correct these issue by changing the instantiation of the vector to have str2.length()+1 instead of str2.length():

      std::vector<std::vector<int>> strMat(str1.length()+1,std::vector<int>(str2.length()+1,0));