3
votes

I am having a segmentation fault while running this code: http://ideone.com/yU80Bd

The problem is when I run it in GDB, the code runs fine and excellent. Why is this running in gdb with no segfault but running every other place with a segmentation fault?

Here is the problem I am trying to solve: http://www.codechef.com/DEC13/problems/CHODE

1
You might want to look at possible race conditions - Paul Evans
what is race condition? - Unbound
@Unbound: a term you can google. - PlasmaHH
Can you narrow down the code at all? Post a shorter testcase here inline? - Lightness Races in Orbit
@PaulEvans The code the OP links to is single-threaded. Why would there be races? - user2363448

1 Answers

3
votes

The problem is that your input includes characters that are not in the range [a-Z]. For example: ! That causes the vector to be accesed 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);
    }