title: C dynamic struct (malloc and free)
body: <p>I am trying to learn the basics of C, C++ programming, so I've started with "C".
  I have lots of experience programming with Java and VB. But "C" is what I want to learn.
  So I'm having an issue, trying to understand the "malloc" and "free" functions.</p>
  
  <p>I am using Borland C++ 4.5 and Visual C++ 6.0 on Windows 98. - (Just a testing environment, want to learn the very basic and early windows programming).</p>
  
  <p>Refer to this code:</p>
  
  <pre><code>struct String
  {
   char *value;
   int length;
  };
  char *initString(const char *value)
  {
   char *str = (char*)malloc( strlen(value)+1 );
   strcpy(str, value);
   return str;
  }
  
  struct String *InitString(const char *text)
  {
   struct String *str = (struct String*)malloc( sizeof(struct String) );
  
   str-&gt;value = initString(text);
   str-&gt;length = strlen( str-&gt;value );
   return str;
  }
  void freeString(struct String *str)
  {
   free(str-&gt;value);
   free(str);
   str = NULL;
  }
  int main(int argv, char *argc[])
  {
   struct String *theString = InitString("Testring string struct");
  
   printf("String: %s\n", theString-&gt;value);
   printf("String Length: %d\n", theString-&gt;length);
  
   freeString(theString);
  
   printf("\nData: %s", theString-&gt;value);
  
   return 0;
  }
  </code></pre>
  
  <p>When this program runs, the result is correct.<br>
  After I call "<code>freeString(theString)</code>", the function does free the memory and set the
  struct to NULL inside the "freeString()" function, that should free the "theString" inside "main()" as I pass in the pointer to "theString", but when the function returns: "theString" is not "NULL".</p>
  
  <p>On Borland 4.5 I can still call the "printf" with "theString->value" and it prints the string.
  On Visual C++ the program crashes when calling "printf" - BUT "theString" is still not "NULL".
  When I trace the program in debug mode, the "struct" is being freed inside the "freeString()" function and the struct is set to NULL, but when the function returns the "theString" is not NULL and the "value" is still usable on Borland, but not on Visual C++.</p>
  
  <p>So I'm trying to understand, what is going on here?
  Is there some de-reference that should be done?</p>
  
  <p>Thank you in advance!</p>