0

I managed to condense the code where the problem occurs to this:

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

typedef struct
{
    double height;
    double hello;
}Variables;     

void information(Variables **Constants);
int main()
{
    Variables *Constants=NULL;
    information(&Constants);        //Assigns values to the structure pointer

    printf("Height %lf \n",Constants->height);          //These print correctly only
    printf("hello %lf \n",Constants->hello);           //intermittently 
    return(0);
}

void information(Variables **Constants)     //Assigns values structure pointer
{
    Variables *consts,constants;

    constants.height=10;
    constants.hello=20;

    consts=&constants;
    *Constants=consts;

    printf("Height %lf \n",constants.height);          //These always print correctly
    printf("hello %lf \n",constants.hello);   
    return;

}

From what i understand, this code should create a structure pointer in main, *Constants. This pointer is then passed into the function using information(&Constants). In information() another pointer is created and assigned a structure variable. The variable is then filled and the pointer is assigned to *Constants, allowing the entire struct to then be passed back to main().

If i print the structure inside information(), the values are correct. However if i print the values in main() the values are sometimes correct, or they print random numbers. Any help in understanding this would be appreciated.

  • 2
    http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – Mat Mar 09 '16 at 15:47

1 Answers1

2

You are returning a local variable from function. this is causing problem.

when the program exists from function information() the variable constants whose address you use in main is already out of scope.
To solve this problem you need to create the object in function information() using dynamic allocation. and deallocate this memory dynamically allocated in main.

LearningC
  • 3,182
  • 1
  • 12
  • 19
  • 1
    ...and free it before the end of main. – LPs Mar 09 '16 at 15:51
  • Surely the value is "saved" from the local scope as it is assigned to something in a higher scope via a pointer? And if this problem is to do with scope, why does the dynamic allocation not fall into the problem of scope? – Industrialactivity Mar 09 '16 at 16:20
  • this local variable is allocated memory in stack so the memory gets deallocated when the function returns. dynamic memory allocates memory in heap and will not deallocate when function returns. you need to read about c memory layout, diifferent storage classes in C and static vs dynamic memory allocation. these concepts will help in better understanding c program – LearningC Mar 09 '16 at 16:51
  • Thank you very much, very helpful :) – Industrialactivity Mar 09 '16 at 17:20