title: Why does "malloc(): corrupted top size" error get fixed when I have printf() before/after it?
body: <p>Given an absolute path I am trying to get the part that comes after a certain directory. <code>getTargetPath</code> function does that and when I compile and run the code below, the code gives me the expected output. </p>
  
  <p>The problem is when I remove the <code>printf("\n")</code> before the line with <code>malloc</code> in main, I get:  </p>
  
  <p><em>malloc(): corrupted top size<br>
  Aborted (core dumped)</em>  </p>
  
  <p>So when I put a <code>printf("\n")</code> before or after the line with <code>malloc</code> the code seems to work fine but when I remove it, I get the error above.</p>
  
  <p>My question is, why does this happen? I am not asking for a solution to my problem with the path string. I just want to learn what causes this behavior.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  
  
  const char* getTargetPath(const char* source)
  {
      int count = 0;
      int i = 0;
  
      while(*source)
      {
          if (*source == '/')
          {
              ++count;
              if (count == 4)
              {
                  break;
              }
          }
          ++source;
      }
  
      return source;
  }
  
  
  int main()
  {
      const char* backup_path = "/home/ofy/real_2";
      char temp1[] = "/home/dir1/dir2/dir3/dir4/dir5";
      const char* s1 = temp1;
  
      const char* s2 = getTargetPath(s1);
  
      printf("\n");
      char* full_path = (char*)malloc(strlen(backup_path) * sizeof(char));
  
      strcpy(full_path, backup_path);
      strcat(full_path, s2);
  
      printf("%s\n", full_path);
  
      return 0;
  }
  </code></pre>