Reputation: 47
I'm using global structure so I can set/get error or state from everywhere. It was working fine, now I'm in trouble.
structure
typedef struct program Program;
struct program
{
int error;
int state;
};
// global declarations
Program *program;
init
void init_memory(void)
{
program = malloc(sizeof(Program));
if(program == NULL)
{
print_error(E_MEM_ALLOC);
exit(EXIT_FAILURE);
}
program->state = S_NONE;
program->error = E_OK;
}
here program crashes, when I remove "program->error = ...." program is working fine...i don't know why :/
void check_file(char *filename)
{
FILE *file = fopen(filename, "r");
if(file == NULL)
{
program->error = E_FILE_OPEN;
return;
}
fclose(file);
}
whole program: http://pastebin.com/dwSVQ9x8
Upvotes: 1
Views: 155
Reputation: 42159
Making program
a pointer seems unnecessary, why not just make it the actual struct
:
Program program = { .error = E_OK, .state = S_NONE };
Then you don't need to worry about allocating it (and can indeed remove init_memory
altogether). Just change access to its members to use .
instead of ->
, i.e., program.error = E_FILE_OPEN
.
Upvotes: 2