How would I free memory allocated to a pointer in C? -
i have function in c adds new question head of singly linked list:
int addquestion() { unsigned int acount = 0; question* tempquestion = malloc(sizeof(question)); tempquestion->text = malloc(500); fflush(stdin); printf("add new question.\n"); printf("please enter question text below:\n"); fgets(tempquestion->text, 500, stdin); printf("\n"); fflush(stdin); printf("how many answers there?: "); scanf("%u", &tempquestion->numanswers); fflush(stdin); tempquestion->answers = malloc(sizeof(answer*) * tempquestion->numanswers); (acount = 0; acount < tempquestion->numanswers; acount++) { tempquestion->answers[acount] = malloc(sizeof(answer)); tempquestion->answers[acount]->content = malloc(250); printf("enter answer #%d: \n", (acount + 1)); fgets(tempquestion->answers[acount]->content, 250, stdin); fflush(stdin); printf("is correct or wrong? correct = 1, wrong = 0: "); scanf("%u", &tempquestion->answers[acount]->status); fflush(stdin); } tempquestion->pnext = exam.phead; exam.phead = tempquestion; printf("\n"); fflush(stdin); return 1; }
as can see, using malloc() allocate space need new question. however, if try call free() on tempquestion, removes question exam. not want remove question unless question deleted or program terminates.
i have cleanup function supposed free() used memory, not free tempquestion in addquestion() function.
void cleanup() { unsigned int = 0; question* tempquestion = null; if (exam.phead != null) { while (exam.phead->pnext != null) { tempquestion = exam.phead; exam.phead = tempquestion->pnext; (i = 0; < tempquestion->numanswers; i++) { free(tempquestion->answers[i]->content); free(tempquestion->answers[i]); } free(tempquestion->pnext); free(tempquestion->text); free(tempquestion); } free(exam.phead); } }
how free() tempquestion in addquestion() function frees memory when execution ends? i'm using visual studio c++ 2012 have write using c syntax (no c++). new c programming well. thanks!
to answer question: don't. should not call free(tempquestion)
in addquestion
function, because free memory allocated.
when assign pointer pointer, it's pointer copied, not points to.
Comments
Post a Comment