Search code examples
cmemory-leaksvalgrindrealloccs50

How is my (custom) program leaking memory? I am preparing myself for pset5


I'm trying to understand how memory allocation and pointers work, since i find a problem set of CS50 (pset5) too overwhelming.

I made a simple program that reads characters from an array, and let them be written into both a new text file, and into the terminal.

The program works, but it is leaking memory. Specifically for each \n encountered in the string, valgrind states that it loses memory in 1 more block. And for each character in the string (of char *c), it states that 1 more byte is leaked.

What am i doing wrong?

image link of the terminal: https://i.sstatic.net/ANtAs.png

  #include <stdio.h>
  #include <string.h>
  #include <stdlib.h>

  int main (void)
  {

     FILE *fp;
     char *c = "One\nTwo\n";

     // Open file for writing (reading and writing works too, we can use 'w+' for that).
     fp = fopen("file.txt", "w");

     // Write data to the file.
     fwrite(c, strlen(c), 1, fp);

     // Seek to the beginning of the file
     fseek(fp, 0, SEEK_SET);

     // close file of the file pointer (the text file).
     fclose(fp);

     // initialize a counter for the amount of characters in the current word that is being read out of the file.
     int char_count = 0;

     // initialize an address for the first character in a string.
     char *buffer_temp_word = NULL;

     // Read and display data, using iterations over each character.
     // Open the file in read mode.
     fp = fopen("file.txt", "r");

     // initiate a for loop.
     // condition 1: getting a character from the fp stream does not equal reaching the end of the file
     // condition 2: the amount of iterations is not above 60 (failsafe against endless loops).
     for (int i = 0; fgetc(fp) != EOF && i <= 60 ; i++)
     {
        //add a counter to the amount of characters currently read.
        char_count++;
        // seek the pointer 1 place back (the 'IF' function moves the pointer forward 1 place forward for each character).
        fseek(fp , -1L, SEEK_CUR);
        // get the character value of the current spot that the pointer of the read file points to.
        char x = fgetc(fp);
        buffer_temp_word = realloc(buffer_temp_word, (sizeof(char)) * char_count);

        //the string stores the character on the correct place
        //(the first character starts at memory location 0, hence the amount of characters -1)
        buffer_temp_word[char_count - 1] = x;

        // check for the end of the line (which is the end of the word).
        if(x == '\n')
        {
           //printf("(end of line reached)");
           printf("\nusing memory:");

           // iterate trough characters in the memory using the pointer + while loop, option 2.
           while(*buffer_temp_word != '\n')
           {
              printf("%c", *buffer_temp_word);
              buffer_temp_word++;
           }

           printf("\nword printed succesfully");
           // reset the pointer to the beginning of the buffer_temp_word string (which is an array actually).
           buffer_temp_word = NULL;
           free(buffer_temp_word);

           // reset the amount of characters (for the next word that will be read).
           char_count = 0;
        }
        printf("%c", x);
     }
     fclose(fp);
     free(buffer_temp_word);
     return(0);
  }

Solution

  • You set buffer_temp_word to NULL before freeing it:

    // reset the pointer to the beginning of the buffer_temp_word string (which is an array actually).
    buffer_temp_word = NULL;
    free(buffer_temp_word);
    

    If you use clang's static analyzer, it can walk you through a path in your code to show your memory leak.

    Also, setting a pointer to NULL does not reset it to the starting position of the array it points to, it sets it to, well, NULL. Consider using a for-loop instead of your while loop and use the counter to index your array:

    for(int j = 0; buffer_temp_word[j] != '\n'; ++j)
    {
        printf("%c", buffer_temp_word[j]);
    }
    

    And then don't set buffer_temp_word to NULL and don't free it immediately after this loop. The program is already set to realloc it or free it later.