Search code examples
cmallocfgets

Reusing memory space allocated by malloc()


I am a newbie to C and have a couple questions regarding the usage of malloc(): Is it OK to reuse a block of memory allocated? More specifically, what I am trying to do is as below (trying to parse a file using fgets):

#include <stdio.h>
#include <stdlib.h>
main() {
    /*... some code here to open a file and give pointer to fp */

    char *s=(char*) malloc(MAX_CHAR_IN_LINE);

    do {
        //QUESTION: is this right to reuse s in each iteration?
        fgets(s,MAX_CHAR_IN_LINE,fp);
    } while (*s!=NULL);

    free(s);
}

Thank you!


Thanks for the answer! Below is a summary of relevant follow-up Q/As

Q: I fear following situation might happen: In 1st iteration, 5 char were read in, say "abcde"; In 2nd iteration, only 3 char were read in, (a shorter line), say, "fgh". do I end up with "fghde" which seems odd? – user3424826

A: In C, strings are null-terminated. So yes, some of the old string will still be there, but there will be a NUL character that marks the end of the new string. In the future, if you have a specific concern (like that one), present it upfront, so that it can be addressed without all the back-and-forth. It just wastes everyone's time. – Jonathon Reinhart

Q: Maybe I shall rephrase my question as this: is it necessary to clear the allocated space each time before reusing it? (purge every byte before reusing it)

A: The answer to that question is: It depends. If it is a C-string you're working with, then no, its unnecessary (because of the null-terminator, like I mentioned). If it's a dynamically-allocated (malloc'd) struct, then yes, you should memset(p, 0, sizeof(*p)), or manually set every member to zero. – Jonathon Reinhart


Solution

  • Yes, that's okay. between 'malloc' and 'free', the memory is yours to do what you wish with it.

    I should add: if malloc fails it will return 0 (an invalid address). If that happens your example will segfault on the first iteration. To account for this, you may modify your program as follows:

    #include <stdio.h>
    #include <stdlib.h>
    int main() {
        /*... some code here to open a file and give pointer to fp */
    
        char *s=(char*) malloc(MAX_CHAR_IN_LINE);
        if(s == NULL) {
            printf("Error: malloc failed.");
            return 1;
        }
    
        do {
            //QUESTION: is this right to reuse s in each iteration?
            fgets(s,MAX_CHAR_IN_LINE,fp);
        } while (*s!=NULL);
    
        free(s);
        return 0;
    }