Ellis
Ellis

Reputation: 105

Segmentation Fault in C due to pointer

I have recently started coding in C, and am doing some stuff on project Euler. This is my code for challenge three so far. The only problem is when I run the compiled code it throws a segmentation fault. I think it may be due to a pointer I called, the suspect pointer is underneath my comment. I did some research into the subject but I cant seem to be able to fix the error. Any advice?

#include <stdio.h>
#include <stdbool.h>
#include <math.h>

bool is_prime(int k);
int * factors(int num);

int main(){
    int input;
    while (true){
        printf("Enter a number to get the prime factorization of: ");
        scanf("%d", &input);
        if (is_prime(input) == true){
            printf("That number is already prime!");

        }else{
            break;
        }
    }

    //This is the pointer I think is causing the problem
    int * var = factors(input);
    int k;
    for (k = 0; k < 12; k++){
        printf("%d", var[k]);
    }
}

bool is_prime(int k){
    int i;
    double half = ceil(k / 2);
    for (i = 2; i <= half; i++){
        if (((int)(k) % i) == 0){
            return false;
            break;
        }
    }
    return true;
}

int * factors(int num){
    int xi;
    static int array[1000];
    int increment = 0;
    for (xi = 1;xi < ceil(num / 2); xi++){
        if (num % xi == 0){
            array[increment] = xi;
            increment++;
        }
    }
}     

Upvotes: 0

Views: 86

Answers (2)

4pie0
4pie0

Reputation: 29744

Your function is declared as

int * factors(int num);

but it's definition doesn't return anything and yet you are using it's return value in assignment. This triggers undefined behavior. It will compile if compiled without rigorous warnings and the return value will most likely be whatever random value happened to be left in the return register (e.g. EAX on x86).


C-99 Standard § 6.9.1/12 Function definitions

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 362037

The factors function has no return statement. It's supposed to return a pointer but it doesn't return anything.

Side note: Enable your compiler's warnings (e.g., with gcc -Wall -Wextra). If they're already enabled don't ignore them!

Upvotes: 3

Related Questions