title: malloc function crash
body: <p>I have a problem with memory allocation using malloc.
  Here is a fragment from my code:</p>
  
  <pre><code>    printf("DEBUG %d\n",L);
      char *s=(char*)malloc(L+2);
      if(s==0)
      {
        printf("DEBUGO1");
      }
      printf("DEBUGO2\n");
  </code></pre>
  
  <p>It outputs "DEBUG 3",and then a error msgbox appears with this message:</p>
  
  <blockquote>
    <p>The instruction at 0x7c9369aa referenced memory at "0x0000000".   The
    memory could not be read</p>
  </blockquote>
  
  <p>For me such behavior is very strange.
  What can be wrong here?</p>
  
  <p>The application is single threaded.</p>
  
  <p>I'm using mingw C compiler that is built in code::blocks 10.05</p>
  
  <p>I can provide all the code if it is needed.
  Thanks.</p>
  
  <p><strong>UPD1:</strong>
  There is more code:</p>
  
  <pre><code>char *concat3(char *str1,char *str2,char *str3)
  {
      /*concatenate three strings and frees the memory allocated for substrings before*/
      /* returns a pointer to the new string*/
  
      int L=strlen(str1)+strlen(str2)+strlen(str3);
      printf("DEBUG %d\n",L);
      char *s=(char*)malloc(L+2);
      if(s==0)
      {
        printf("DEBUGO1");
      }
      printf("DEBUGO2\n");
      sprintf(s,"%s%s%s",str1,str2,str3);
      free(str1);
      free(str2);
      free(str3);
      return s;
  }
  </code></pre>
  
  <p><strong>UPD2:</strong>
  It seems the problem is more complicated than i thought. Just if somebody has enough time for helping me out:</p>
  
  <p>Here is all the code</p>
  
  <p><a href="http://wikisend.com/download/131726/cbproj.zip" rel="nofollow">Proj</a></p>
  
  <p>(it is code::blocks 10.05 project,but you may compile the sources without an ide ,it is pure C without any libraries):</p>
  
  <p>call the program as
  "cbproj.exe s.pl" (the s.pl file is in the root of the arhive)</p>
  
  <p>and you may see it crashes when it calls  the function "malloc" that is on the 113th line of "parser.tab.c"(where the function concat3 is written). </p>
  
  <p>I do the project in educational purpouses,you may use the source code without any restrictions.</p>
  
  <p><strong>UPD3:</strong>
  The problem was that it was allocated not enough memory for one of the strings in program ,but the it seemed to work until the next malloc.. Oh,I hate C now:)
  I agree with the comments about bad coding style,need to improve myself in this.</p>