-1

I have a quiz game in C where I am using a struct to save when a user enters a wrong answer and the corresponding correct answer to that question. First I used malloc to allocated memory for a single struct.

Struct:

  typedef struct
  {
      char* wrongAnswers;
      char* corrections;
  } Corrections;

Malloc:

  Corrections* corrections = (Corrections*)malloc(sizeof(Corrections));

Later on in my program, I have functionality where a wrong answer increments an 'incorrectAnswers' variable, which is used to reallocate the memory to allow for the new wrong answer to be stored, along with its corresponding correct answer.

Code:

// Extract characters from file and store in character c 
for (c = getc(fPointerOpen); c != EOF; c = getc(fPointerOpen)) {
if (c == '\n') // Increment count if this character is newline 
        numberOfLines++;
}

for (int i = 0; i < numberOfLines; i++) {
    int lengthOfQuestion = 150;

    if (v == 0) {
        printf("Correct\n");
        score++;
    }
    else {
        printf("Incorrect\n");
        incorrectAnswers++;

        corrections = (Corrections*)realloc(corrections, incorrectAnswers * sizeof(Corrections));
        corrections[i].wrongAnswers = malloc(sizeof(char) * lengthofanswer);
        corrections[i].wrongAnswers = lines[i].userAnswers;
        corrections[i].corrections = malloc(sizeof(char) * lengthofanswer);
        corrections[i].corrections = lines[i].answers;

    }
    printf("Your score is %d/%d\n", score, (i + 1));
  }

I am receiving a bug depending on the order in which right and wrong answers are input. I have tried using free() in different parts of the program and I have noticed that the bug will always appear when I enter a wrong answer as the last entry in my program/if I enter a right then wrong answer. Why is this the case? My understanding is I am implementing realloc incorrectly.

Gearoid Sheehan
  • 198
  • 1
  • 19
  • `corrections[i].wrongAnswers = malloc(sizeof(char) * lengthofanswer); corrections[i].wrongAnswers =` just leaks memory. `var = malloc(...); var = something` is always wrong. The `implementing realloc` would mean that you yourself are writing `realloc` internals. Your code _uses_ `realloc`, you don't implement `realloc`, you implement something that uses `realloc`. You have to show more code. What is `i`? What is `lengthofanswer`? And [no need to cast result of *alloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – KamilCuk May 09 '20 at 19:36
  • I updated my code to include the values for 'i' and 'lengthofanswer' – Gearoid Sheehan May 10 '20 at 14:37

1 Answers1

1

you should use strcpy to copy string, do not use = to assign string in c.

strcpy(corrections[i].wrongAnswers,lines[i].userAnswers);

strcpy(corrections[i].corrections,lines[i].answers);

Each time you use malloc or realloc, you should check the return value of these functions.

Hitokiri
  • 3,607
  • 1
  • 9
  • 29