What is the difference between the values of these two char arrays?

Viewed 47

I'm working on code in C that reads the temperature and sends it to a GUI made with GTK3.

Here is the code:

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

char Vo[10];         // voltage out
float Ro, R1 = 6247; // value of resistance at 20C in the thermistor
float T0 = 298.15;   // 25 degrees C in Kelvin
float logR2, R2, T;
float A = 1.281426510e-03, B = 2.368116050e-04, C = 0.9002008458e-07;  // Steinhart-Hart and Hart Coefficients

char *senseTemp() {
    FILE *fp;
    char command[50];
    int c;

    //get the Analog value
    fp = fopen("/sys/bus/iio/devices/iio:device0/in_voltage0_raw", "r");
    if (fp == NULL) {
        perror("Error: ");
        return (1);
    }
    int i = 0;
    while (1) {
        c = fgetc(fp);
        if (feof(fp)) {
            break;
        }
        printf("%c ", c);
        if (c != EOF) {
            Vo[i] = c;
            ++i;
        }
    }

    fclose(fp);
    
    //printf("Analog Reading: %s\n", Vo);
    
    //convert the value to resistance
    int V = 0;
    float Vout = 0;
    V = atoi(Vo);           //TO convert an array to an integer
    //printf("Value of V: %d\n", V);
    
    Vout = V * (1.8 / 4095.0);      //Voltage out of the thermistor
    //printf("Voltage out from thermistor: %f\n", Vout);
    
    R2 = R1 * ((1.8 / Vout) - 1);
    
    logR2 = log(R2);
    T = (1.0 / (A + B * logR2 + C * logR2 * logR2 * logR2));  // Steinhart and Hart Equation. T  = 1 / {A + B[ln(R)] + C[ln(R)]^3}
    
    T =  T - 273.15;
    
    char Tfinal[10];
    i = 0;
    
    snprintf(Tfinal, 10, "%.0f", T);
    printf("Here is the value: %s\n", Tfinal);
    
    return Tfinal;
}

If I use return Vo; the values are properly returned to the GUI and I can see them, but I want to convert the values to degrees celsius and that is what the variable T holds. But the gtk_label_set_text() that displays the temperature in the GUI only takes a pointer to a string.

So in my code if I use return Vo it works but not with return Tfinal.

2 Answers

return Tfinal; has undefined behavior because you return the address of an array with local automatic storage. This array is discarded upon funtion return. Allocate the array with malloc() to return it to the caller.

Tfinal is an array local to the function. That means when you use return Tfinal; you're returning a pointer to the first element of the array. So you're returning a pointer to a variable whose lifetime has ended. Dereferencing such a pointer (or even reading it) invokes undefined behavior. In contrast, Vo is defined at file scope and therefore has full program lifetime.

You need to either allocate memory dynamically and return that (and free the memory when you're done with it), declare the array static so its lifetime is that of the full program, or move the definition to file scope.

Related