-2

So I was trying to print the result of a function from main, but for some reason, I get the error signal: segmentation fault (core dumped). My program is supposed to calculate all of the expressions by reference, and call and print the result from main().

here's the code:

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

void prodDivPowInv(float a, float b, float *prod, float *div, float *pwr, float *invb);

int main() {
  float x, y;

  scanf("%f", &x);

  scanf("%f", &y);
  float *prod_1, *div_1, *pwr_1, *invb_1;

  prodDivPowInv(x, y, prod_1, div_1, pwr_1, invb_1);

  printf("product=%f\n", *prod_1);
  printf("division=%f\n", *div_1);
  printf("power b of a=%f\n", *pwr_1);
  printf("inverse of b=%f\n", *invb_1);

  return 0;
}

void prodDivPowInv(float a, float b, float *prod, float *div, float *pwr,
                   float *invb) {
  (*prod) = a * b;
  (*div) = a / b;
  (*pwr) = pow(a, b);
  (*invb) = 1 / b;
}
Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • 1
    `float *prod_1, *div_1, *pwr_1, *invb_1;` are pointers but you haven't allocated any memory. Where do you expect `(*prod) = a * b;` to write the result? – Ted Lyngmo Oct 02 '22 at 19:07
  • Please indent your code properly and don't put a blank line between each and every line of your code. IOW use the same style as the samples in your learning material – Jabberwocky Oct 02 '22 at 19:09
  • Welcom to SO. Note that the title of your question is almost certainly wrong. It would be very unusual for a compiler to end with a seg fault. I think you're saying that your program ends with a seg fault after the compiler is done working on it and you've run the executable that it produced. – Gene Oct 02 '22 at 20:24

1 Answers1

0

float *prod_1, *div_1, *pwr_1, *invb_1; are pointers but they are not pointing at any allocated memory, so when you dereference these pointers, like in (*prod) = a * b;, it'll have undefined behavior.

Instead, declare the variables as normal variables and take their addresses (&):

float prod_1, div_1, pwr_1, invb_1; // not pointers

// here, take their addresses:
proddivpowinv(x, y, &prod_1, &div_1, &pwr_1, &invb_1);

printf("product=%f\n", prod_1);
printf("division=%f\n", div_1);
printf("power b of a=%f\n", pwr_1);
printf("inverse of b=%f\n", invb_1);
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108