title: Why no memory leak?
body: <p>The following is designed to take a variable length constant char and print it out in a nice format for logging.  I am certain readers will have suggestions on how this can be improved, and I'd welcome it.</p>
  
  <p>What puzzles me is that I expected it would be necessary to free() the returned static char each time ToHexString() is called.  Instead, I see no memory leak whatsoever.  Even tho I use the function inline and therefore do not assign its return value to a variable.</p>
  
  <p>I created a simple test that calls this function in a loop, each time with a different length cString and nMaxChars parameter.  Then I watched VM status.  The memory allocation for my test program, and free memory, never changed.</p>
  
  <p>It seems to me it should have increased each time a malloc is called and no free.</p>
  
  <pre><code>static char *ToHexString(const char *cString,int nMaxChars)
  {
      static char *cStr;
  
  
  
      /*if (80&gt;strlen(cString))
          nRawChars=strlen(cString);
      if (nMaxChars&gt;nRawChars)
          nRawChars=nMaxChars;
      */
      if (nMaxChars==0)
          nMaxChars=80;
  
      printf("There are %i chars\n",nMaxChars);
  
      char *cStr1;
      char *cStr2;
      char *cStr3;
      int nLen=nMaxChars*6;
      cStr=calloc(nLen,sizeof(char));
  
      cStr1=calloc(10,sizeof(char));
      cStr2=calloc(nLen,sizeof(char));
      cStr3=calloc(nLen,sizeof(char));
      cStr1[0]='\0';
      cStr2[0]='\0';
      cStr3[0]='\0';
      int nC1=0;
      int nRowCnt=0;
  
      for (nC1=0;nC1&lt;nMaxChars;nC1++)
      {
          ++nRowCnt;
          if (cString[nC1]==0x00)
              snprintf(cStr1,8,"[00] ");
          else
              snprintf(cStr1,8,"[%02x] ",(unsigned char)cString[nC1]);
  
          if ( (nRowCnt%8==0) )
          {
              snprintf(cStr3,nLen,"%s%s\n",cStr2,cStr1);
          }
          else
              snprintf(cStr3,nLen,"%s%s",cStr2,cStr1);
  
          snprintf(cStr2,nLen,"%s",cStr3);
      }
      snprintf(cStr,nLen,"%s",cStr3);
      free(cStr1);
      free(cStr2);
      free(cStr3);
      return(cStr);
  }
  </code></pre>
  
  <p>Here is the calling routine:</p>
  
  <pre><code>for (i=0;i&lt;100;i++)
  {
      memset(&amp;cBuff, 0,255);
      printf("Reading %s now..\n",cPort);
      while (sleep(1)==-1);
      nChars=read(nPort, cBuff, 255);
      //printf("Read %i chars from %s\n",nChars,cPort);
      if (nChars&lt;=0)
          printf("Read 0 chars from %s\n",cPort);
      else
          printf("Read %i chars from %s\n%s\n",nChars,cPort,ToHexString(cBuff,nChars));
  }
  </code></pre>