c - How would I free a pointer malloc'd in a separate function? -
i have global variable called exam of type struct exam:
typedef struct { question* phead; }exam; exam exam;
in function malloc space pointer phead:
int initexam() { exam.phead = malloc(sizeof(question*)); exam.phead = null; return 1; }
in separate function try free memory:
void cleanup() { unsigned int = 0; question* currentquestion = exam.phead; while (currentquestion != null) { // other code } exam.phead = null; }
i have tried following inside function:
free(exam.phead);
my issue not seem free memory allocated malloc. cleanup() free memory allocated exam.phead , cannot change function signatures or move free() calls function. there i'm doing wrong? i'm new c programming. thanks!
you have memory leak, right off:
int initexam() { exam.phead = malloc(sizeof(question*));//assign address of allocated memory exam.phead = null;//reassign member, null-pointer return 1; }
the exam.phead
member assigned address of memory allocated, become null-pointer right after. null pointer can free
'd safely, doesn't do anything.
meanwhile, malloc
'ed memory stay allocated, have no pointer it, , therefore cannot manage it. can't free
memory, nor can use it. take null
assignment attempt initialize memory "clean" value. there ways to this, i'll in moment.
anyway, because phead
null, following statements:
question* currentquestion = exam.phead;//is same currentquestion = null; while (currentquestion != null) //is same while(0)
don't make sense, @ all.
to initialize newly allocated memory, either use memset
, or calloc
. latter initializes allocated block of memory zero, memset
can (calloc
same calling malloc
+ memset
), allows initialize value like:
char *foo = calloc(100, sizeof *foo);// or calloc(100, 1); //is same writing: char *bar = malloc(100); memset(bar, '\0', 100);
Comments
Post a Comment