C. Ben
C. Ben

Reputation: 61

C Floating Point exception (core dumped)

I am a noob studying C and have tried to create a program that provides the highest common divisor of 2 entered numbers. However, after a successful compile, I get the titled error after I enter data to the scanf prompt. I have tried for ever to solve it but cannot. Please ignore the double slashes.

//Declare external libraries and function calls //
#include <stdio.h>
void gcdFunction (int *variable1, int *variable2);

// Main Program//
int main(void)
{
    int firstNumber = 0, secondNumber = 0;
    printf("Please enter first value \n");
    scanf("%d", &firstNumber);
    printf("Please enter second value \n");
    scanf("%d", &secondNumber);
//Call function passing 2 address parameters //
    gcdFunction(&firstNumber, &secondNumber);
}

// Call function, passing parameters as pointers //
void gcdFunction(int *variable1, int *variable2)
{
    int i, z;
    while (i != 0)
    {
        i = *variable2;
        *variable2 = *variable1 % *variable2;
        *variable1 = i;
    }
    z = *variable1;
    printf("\nThe GCD of the two values entered is: %d", z);
}

Upvotes: 1

Views: 426

Answers (2)

barak manos
barak manos

Reputation: 30136

The following piece of code:

int i;
while (i != 0)
{
    i = *variable2;
    *variable2 = *variable1 % *variable2;
    *variable1 = i;
}

Embeds two problems:

  • i is not initialized before being used at while (i != 0)
  • *variable2 may be zero when calculating *variable1 % *variable2

The first problem yields undefined behavior of your program.

The second problem may lead to a divide-by-zero exception.

Upvotes: 2

Ctx
Ctx

Reputation: 18420

The problem is in this loop:

while (i !=0){
    i = *variable2;
    *variable2 = *variable1 % *variable2;
    *variable1 = i;
}

Here, if *variable2 becomes 0 it is used as the modulo right-hand-side in the next iteration, since i is set after checking the loop condition. Change it to

while (*variable2 !=0){
    i = *variable2;
    *variable2 = *variable1 % *variable2;
    *variable1 = i;
}

then the error should no longer occur.

Upvotes: 2

Related Questions