I have a function in C that adds a new Question to the head of a singly linked list:
int AddQuestion()
{
unsigned int aCount = 0;
Question* tempQuestion = malloc(sizeof(Question));
tempQuestion->text = malloc(500);
fflush(stdin);
printf("Add a new question.\n");
printf("Please enter the question text below:\n");
fgets(tempQuestion->text, 500, stdin);
printf("\n");
fflush(stdin);
printf("How many answers are there?: ");
scanf("%u", &tempQuestion->numAnswers);
fflush(stdin);
tempQuestion->answers = malloc(sizeof(Answer*) * tempQuestion->numAnswers);
for (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 it 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 you can see, I am using malloc() to allocate the space I need for the new question. However, if I try to call free() on tempQuestion, it removes the question from the exam. I do not want to remove the question unless the question is deleted or the program terminates.
I have a cleanup function that is supposed to free() up all the used memory, but it does not free up tempQuestion in the addQuestion() function.
void CleanUp()
{
unsigned int i = 0;
Question* tempQuestion = NULL;
if (exam.phead != NULL) {
while (exam.phead->pNext != NULL) {
tempQuestion = exam.phead;
exam.phead = tempQuestion->pNext;
for (i = 0; i < tempQuestion->numAnswers; i++) {
free(tempQuestion->answers[i]->content);
free(tempQuestion->answers[i]);
}
free(tempQuestion->pNext);
free(tempQuestion->text);
free(tempQuestion);
}
free(exam.phead);
}
}
How would I free() tempQuestion in my addQuestion() function so that it only frees the memory when execution ends? I'm using Visual Studio C++ 2012 but I have to write using only C syntax (no C++). I am fairly new to C programming as well. Thanks!