0

The problem is that this code works well for input string of size 4 but for size more than 4 it gives segmentation fault.

The problem is to check the index of all anagrams of a string in another string.

for example: for string1 input abab and string2 input ab - it works good but for BACDGABCDA and ABCD gives segmentation fault.

#include<bits/stdc++.h>
using namespace std;

void anagram(string s, string p) {
    int k = p.length();
    
    string temp = "";
    
    vector<int> v;
    
    int j = 0;
    for(int i = 0;i<p.length();i++) {
        temp += s[i];
    }
    sort(temp.begin(), temp.end());
    for(int i = p.length();i<s.length();i++) {
        
         if(temp == p && i == p.length()) {
            v.push_back(i-k+1);
            continue;
            }
        
           
              temp.erase(temp.begin()+(i-k));
              temp += s[i];
              sort(temp.begin(), temp.end());
              if(temp == p) {
                v.push_back(i-k+1);
              }

    }

     for (auto& it : v) { 
  
        cout << it << ' '; 
    } 
}



int main() {
    // This is to find the starting index of all anagrams in a string.

    string s = "BACDGABCDA";
    string p = "ABCD";

    anagram(s, p);
    return 0;
}
Namandeep_Kaur
  • 368
  • 1
  • 3
  • 11
  • 5
    First See: [Why should I not #include ?](https://stackoverflow.com/q/31816095/3422102), and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/364696) -- Then please provide [A Minimal, Complete, and Verifiable Example (MCVE)](http://stackoverflow.com/help/mcve). What is `p`, what is `s`, etc.. including your MCVE, compiler warnings and associated errors, if any, will allow everyone here to help you with your question. – David C. Rankin Aug 31 '20 at 05:44
  • `for(int i = 0;i s`. – Lukas-T Aug 31 '20 at 06:04
  • @churill Yes, it can but the input that is provided p will always be smaller than s. – love errors Aug 31 '20 at 06:10

1 Answers1

0

Your string temp has always a length of 4. Variable k is const 4. Variable i starts at 4 and goes up to 9. So after some iterations you try to erase elements after the end of your string temp.

Using a debugger or adding some additional checks in your code will provide a faster answer to such issues than just asking others.

SKCoder
  • 409
  • 3
  • 10