title: Reusing memory space allocated by malloc()
body: <p>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):</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  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);
  }
  </code></pre>
  
  <p>Thank you!</p>
  
  <hr>
  
  <p>Thanks for the answer!
  Below is a summary of relevant follow-up Q/As </p>
  
  <p>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 </p>
  
  <p>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</p>
  
  <p>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)</p>
  
  <p>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 </p>