Segmentation fault core dumped : Function that returns the next prime number

Viewed 378

I get segmentation fault core dumped. My function is supposed to return the prime number following the one put in parameters, or to return the number if it is a prime.

When I compile, I have no errors, I also compiled with -Wall, it worked. But when I run the program I get segmentation fault, core dumped. I can't see the issue.

#include <stdio.h>

int ft_next_prime(int nb)
{
        int i = 2;
        int notPrime = 0;

        while (i++ < 9 || notPrime != 1) {
                if (nb == i)
                        i++;
                else if (nb % i == 0)
                        notPrime = 1;
        }
        return ((notPrime) ? ft_next_prime(nb++) : nb);
}

int main()
{
        printf("%d", ft_next_prime(15));
}

why?

Also, can I write this?

while (i++ < 9 || !notPrime)
    if (nb % (i != nb) == 0)
        notPrime = 1;
3 Answers

Use the following line in place of your return statement:

return ((notPrime)? ft_next_prime(nb+1) : nb);

There are a few different causes of a segmentation fault. In your case, you are running out of space on the stack.

The line ft_next_prime(nb++) executes and returns ft_next_prime(nb) — with the exact same parameter — and then increments nb — pointlessly but that's exactly what you told it to do.

"Segmentation fault" means that you tried to access memory that you do not have access to.

The other answers have failed to point out that:

The problem is that you have TWO sources of infinite loop

1) an infinite loop in:

while(i++ < 9 || notPrime != 1)

by having || notPrime != 1 you will iterate until i++ < 9 is false and notPrime is actual 1. In another words you will be iterating until if(nb % i == 0) evaluates to true and variable notPrime is set to 1;

Therefore, in the call

return ((notPrime)? ft_next_prime(nb++) : nb);

it will always call recursively ft_next_prime again, and again. Hence, the infinite loop which ends up causing the Segmentation fault.

You actually meant while(i++ < 9 && notPrime != 1)

2) Furthermore, ft_next_prime(nb++) should be replaced by ft_next_prime(nb+1) otherwise you are calling the recursive function with always the same value.


The other problems that you have is the logic of find the prime number. A number is prime :

A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.

You stop checking at i++ < 9 which makes no sense because a 143 = 11 * 13 is not prime since it is divisible by 11 and 13. You need to check at least until nb / 2 (actually there is even a better lower boundary that I will leave for you to find).


A possible solution :

#include <stdio.h>

int ft_next_prime(int nb){
        int notPrime = 0;
        for(int i = 2; i < nb / 2 && !notPrime; i++)
            notPrime = nb % i == 0;
        return notPrime ? ft_next_prime(nb + 1) : nb;
}

int main() {
     printf("%d", ft_next_prime(15));
}
Related