+ 2
Why i am getting segmentation fault for calling same function twice
this is the function here mp contains value and key string morseToWord(string input, map<string,string> mp, map<string,string>::iterator it) { input += " "; string decoded = "",a = ""; for(int i = 0; i < input.length(); i++) { if(input[i] != ' ' && input[i] != '/') { a += input[i]; } else if(input[i] == ' ') { it = mp.find(a); decoded += it->second; a = ""; } else if(input[i] == '/') decoded += " "; } return decoded; } it works perfectly fine when calling it once but gives segmentation fault every time i call the function twice in the main function.
3 odpowiedzi
+ 2
A segmentation fault generally occurs when you try to access memory that is not allocated for you i.e outside the boundary of the current program. If you give a link to the full code, I can try to give some explanation for the same.
+ 2
You should really pass references or pointers in your function parameters if you want to modify parameters inside the function. But I would need to see the whole code to know the problem.
+ 1
the problem is the whole code is somewhat 100-200 lines long so i can't write it here. but it is like this.
#include <iostream>
#include <map>
using namespace std;
string morseToWord(string input, map<string,string> mp, map<string,string>::iterator it);
int main() {
map<string,string>key;
map<string,string>::iterator it;
key["A"] = "..-";
// and so on
key["..-"] = "A";
// and so on till all the letters and same for morse code as well
cout << morseToWord("-",key, it) <<endl;
cout << morseToWord("-",key, it) <<endl;
}
string morseToWord(string input, map<string,string> mp, map<string,string>::iterator it) {
input += " ";
string decoded = "",a = "";
for(int i = 0; i < input.length(); i++) {
if(input[i] != ' ' && input[i] != '/') {
a += input[i];
}
else if(input[i] == ' ') {
it = mp.find(a);
decoded += it->second;
a = "";
}
else if(input[i] == '/')
decoded += " ";
}
return decoded;
}
*morse code in the code may be wrong, only purpose is to show logic