Juanker
Juanker

Reputation: 794

Segmentation fault(core dumped) on OpenMP loop

I have an algorithm that looks for a string inside another string, and with some very long strings I got:

Segmentation fault (core dumped)

An that is my code where: S is the string that is looked for, and B is the big string that maybe contains the S string

int search( char *S, int sizeS, char *B, int sizeB )
{
    int result = -1;

    #pragma omp parallel shared(result)
    {
        int startB, thread, threads, length;

        threads = omp_get_num_threads();
        thread = omp_get_thread_num();

        length = sizeB / threads;

        for(startB = length * thread; result==-1 && startB <= startB+length; startB++ ) {
            int ind;

            for( ind = 0; ind < sizeS; ind++ ) {
                if ( S[ind] != B[startB+ind] )  break;
            }

            if ( ind == sizeS && result == -1)
                result = startB;
        }
    }
    return result;
}

Upvotes: 0

Views: 499

Answers (1)

Mathieu
Mathieu

Reputation: 9619

I found two typos in your code:

Wrong for loop condition (which cause the crash):

for(startB = length * thread; result==-1 && startB <= startB ; startB++ ) 

Should be:

for(startB = length * thread; result==-1 && startB <= sizeB ; startB++ ) 

Then, the ind test seems wrong (which prevent to find the substring):

if ( ind == sizeS && result == -1)
    result = startB;

Should be

if ( ind == (sizeS - 1) && result == -1)
    result = startB;

Upvotes: 1

Related Questions