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;
       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;
       int num = 26;

       for(int x = 25; x >= 0; x--)
           sum = sum + (arr[x]*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

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 !!

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.


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

1 Like

If you have less memory then also this might happen…

problem link ??

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

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: