Reputation: 335
I am having a segmentation fault while running this code:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class cipher {
public:
char letter;
int frequency;
};
bool comp(const cipher &A, const cipher &B) {
if(A.frequency<B.frequency)
return true;
else
return false;
}
vector<cipher> cipherF;
int posOf(char c)
{
int i;
for(i=0; i<26; ++i)
if(cipherF[i].letter == c)
return i;
return -1;
}
int main()
{
int t;
cin >> t;
string tmp;
getline(cin, tmp);
while(t--) {
cipherF.clear();
for(int i=97; i<=122; ++i)
{
cipher cip;
cip.letter = i;
cip.frequency = 0;
cipherF.push_back(cip);
}
string txtF, cipherText;
getline(cin, txtF);
getline(cin, cipherText);
for(int i=0; i<cipherText.size(); ++i)
{
char c = tolower(cipherText[i]);
++(cipherF[c-97].frequency);
}
stable_sort(cipherF.begin(), cipherF.end(), comp);
for(int i=0; i<cipherText.size(); ++i)
{
int pos = posOf(cipherText[i]);
if(pos == -1)
continue;
else if(isupper(cipherText[i]))
cipherText[i] = toupper(txtF[pos]);
else
cipherText[i] = txtF[pos];
}
cout << cipherText << endl;
}
}
The problem is when I run it in GDB, the code runs fine and excellent. Why is this running in GDB without any segmentation fault, but running at every other place with a segmentation fault?
Here is the problem I am trying to solve: http://www.codechef.com/DEC13/problems/CHODE
Upvotes: 3
Views: 2072
Reputation: 2897
The problem is that your input includes characters that are not in the range [a-Z]
. For example: !
That causes the vector to be accessed at invalid indexes.
You can check these things running your program with valgrind
.
valgrind ./ideone < stdin
...
==2830== Invalid read of size 4
==2830== at 0x40111A: main (ideone.cpp:53)
...
==2830== Invalid write of size 4
==2830== at 0x401120: main (ideone.cpp:53)
The problem is in these lines:
for(int i=0;i<cipherText.size();++i)
{
char c = tolower(cipherText[i]);
++(cipherF[c-97].frequency);
}
c - 97
may be lower than 0.
You can check, for example:
for(int i=0;i<cipherText.size();++i)
{
char c = tolower(cipherText[i]);
if (c < 'a' || c > 'z') continue;
++(cipherF[c-97].frequency);
}
Upvotes: 3