segmentation fault?

can someone please identify why I am getting segmentation fault in this code?

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[]) {
    ifstream stream(argv[1]);

   string str;
   while(getline(cin,str,'\n'))
   {
       int sum = 0;
       int length = str.length();
       for(int x = 0; x < length; x++)
        str[x] = tolower(str[x]);
       int arr[26] = {0};
       int index = 0;
       for(int x = 0; x < length; x++)
       {
           index = str[x] - 97;
           arr[index]++;
       }
       sort(arr,arr+26);
       int num = 26;

       for(int x = 25; x >= 0; x--)
       {
           sum = sum + (arr[x]*num);
           num--;
       }
       cout << sum << endl;
   }
return 0;
}

it is running completely fine on my pc’s compiler, i dont know why codeeval(yes this is for a codeeval problem) doesnt accept this code

PS
i am getting the same answer from the test cases. but my question is about the segfault

when the RAM has memory allocation problem then code gives segmentation fault as i observe !!

problem link ??


here it is, can you point out where my code gets the error?

The string may contain other characters like punctuation marks,semicolon etc. So you need to avoid those characters. I made some changes (comments added) and it got accepted. You can see my submitted solution here.

You were getting segmentation fault because you were trying access an invalid memory reference in this line.

arr[index]++;

Suppose the character is semicolon , its ASCII value is 59 , then index = 59-97 = -38. (negative index) .

1 Like

This is really a great response, you even tried the problem and find my fault. Thank you for that! :slight_smile:

your welcome :slight_smile:

If you have less memory then also this might happen…