Why can not I print?

0

It's a simple code (I'm practicing pointers) It is not printing the result, the program closes ... why? ;;;

#include <stdio.h>
#include <math.h>
#define PI 3.1416

void calc_esfera(float R, float *area, float *volume);

int main(){
    float raio, *area, *volume;

    printf("Raio: ");
    fflush(stdin);
    scanf("%f", &raio);

    calc_esfera(raio, area, volume);

    printf("Area: %.2f\n", *area);

    printf("Volume: %.2f", *volume);

}

void calc_esfera(float R, float *area, float *volume){

    *area = PI * pow(R, 2.0);
    *volume = 4 * PI * pow(R, 3.0);
}
    
asked by anonymous 27.07.2018 / 14:00

1 answer

5

It turns out you did not initialize the pointers. As the name itself indicates, they are pointers, so you have to point to some location in memory that is where the values are placed.

Soon when it does:

*area = PI * pow(R, 2.0);

You are saying, in the memory location where the area pointer points, enter this value. But where is this? area was not even assigned, so this results in undefined behavior and potentially segmentation fault .

The compiler itself helps you. Here's what I get when I compile your code:

||=== Build: Debug in Test (compiler: GNU GCC Compiler) ===|
... main.c|14|warning: 'area' is used uninitialized in this function [-Wuninitialized]|
... main.c|14|warning: 'volume' is used uninitialized in this function [-Wuninitialized]|
||=== Build finished: 0 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|

How do you fix it? Allocate space for the pointer, which would be the most normal:

float *area = malloc(sizeof(float));
float *volume = malloc(sizeof(float));

Now the pointers already point to a valid location in memory, even though they have no value assigned by you. This will already make the following assignments work correctly. Do not forget to include <stdlib.h> to use malloc .

Alternatively, you would create variables for area and volume as values and pass their addresses to the function:

float area, volume;
...
calc_esfera(raio, &area, &volume);
//                ^------^-- aqui passa o endereço das variáveis no main

This last solution would even be preferable because it avoids allocation in heap , which causes more memory fragmentation and is slower. It also prevents you from having to worry about releasing memory with free when you no longer need it.

    
27.07.2018 / 14:33