yaoshinga
yaoshinga

Reputation: 57

Process exited prematurely with a SIGSEGV signal

This code shows this SIGSEGV error, which I understand, is a segmentation error. Can someone please help! The code returns the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. I am using this on a programming challenge so this is only a function.

So, If I input "aabcdef" it should return 2 because 'a' occurs twice. Input can contain alphabets as well as numerics.

int duplicateCount(const char* in)
{
int a[39]={0},b=0;
for(int i=0;i<strlen(in);i++)
{
    if(in == NULL)
        return 0;


    if((int)in[i] < 97)
    {
        a[(int)in[i]]++;
    }
    a[tolower(in[i])-'a'+1]++;
}

for(int i=0;i<39;i++)
{
    if(a[i]>1)

        b++;
}


return b;

}

Upvotes: 0

Views: 14994

Answers (1)

kocica
kocica

Reputation: 6467

Problem is here

if((int)in[i] < 97)
{
    a[(int)in[i]]++;
}
a[tolower(in[i])-'a'+1]++;

you may write outside of bounds which, as we know, has UB.


Fix

First you have to check if character is letter with isalpha(c)

Then you have to transform character to lower via tolower(c)

And sub the first low case letter in alphabet c - 'a'

Then you can index an array and increment its value.

Here is fixed code


Since we are in , you may use std::map

#include <iostream>
#include <map>

int main()
{
    std::string text("aabbc");
    std::map<char, int> letterCounter;

    for(auto& it : text)
    {
        letterCounter[it]++;
    }

    for (auto& it : letterCounter)
    {
        if (it.second > 1)
        {
            std::cout << "Character " << it.first << " has appeared "
                      << it.second << " times." << std::endl;
        }
    }

    return 0;
}

Output

Character a has appeared 2 times.
Character b has appeared 2 times.

Upvotes: 1

Related Questions