Reputation: 363
Below is complete code
brief summary of my problem is below: I have one global structure as mentioned below in file1.c and its getting initialized with some value in file1.c by function"assign_value()" and now I am printing this value by function "print_value()" from file2.c.
Problem is that: its not printing proper value from file2.c on the other hand if I call "print_value()" from file1.c inside function "assign_value()" as mentioned below then it shows proper value.
Please suggest what I am missing, why I am not able to print proper value by calling print_value() function in file2.c
file1.c
My_struct_one is nested structure containing another structure My_struct_two and my_struct_obj_global is global variable in file1.c
//file1.c
#include <stdio.h>
#include "file1.h"
typedef unsigned long int List;
typedef struct
{
List* my_list;
}My_struct_two;
typedef struct
{
My_struct_two struct_two;
}My_struct_one;
My_struct_one struct_global;
void assign_value()
{
List value=9;
struct_global.struct_two.my_list = &value;
print_value();
}
void print_value()
{
printf("inside print");
printf("value=%u\n",*(struct_global.struct_two.my_list));
}
file1.h //file.h
#ifndef _file1_c
#define _file1_c
void print_value();
void assign_value();
#endif
file2.c #include
#include "file1.h"
int main()
{
assign_value();
print_value();
return 0;
}
OUTPUT: inside printvalue=9 inside printvalue=4195506
Mine doubt is why I cant access value from file2.c,
Upvotes: 1
Views: 200
Reputation: 4430
value
is a local variable in function assign_value()
. It is created when the function is entered, and it is destroyed when the function returns.
In function print_value()
, the value of struct_global.struct_two.my_list
is a dangling pointer: its value is the address of a variable which does not exist any more.
Dereferencing the value of a dangling pointer is undefined behavior.
Upvotes: 1