title: Damaged heap while working with dynamically allocated variables and _chdir windows function
body: <p>while working with those function i'm getting stuck with an error.
  The debbuger says "damged heap" on <code>_chdir(dirCorrente);</code> line.</p>
  
  <p>The main calls those function as follow:
   - char* temp = getCartellaCorrente();
   - some other stuff not relative to these function...
   - temp = setCartellaCorrente("cd test")</p>
  
  <p>when the execution stops the setCartellaCorrente's dirCorrente value is '"C:\Users\Luca\Desktop\remote-control-project\FirstService\Debug\test"'</p>
  
  <p>I think i'm doing something wrong with dynamically allocated variables.</p>
  
  <p>I'm working on this problem since 48 hours now, i've serached on the internet but nothing. I guess that i don't know something important about allocated variable or _chdir function.</p>
  
  <p>I will be really gratefull if you can explain me what i miss.</p>
  
  <pre><code>char* getCartellaCorrente() {
      char* temp;
      size_t size;
      LPWSTR dirCorrente = new TCHAR[DEFAULT_BUFLEN];
      GetCurrentDirectory(DEFAULT_BUFLEN, dirCorrente);
      size = wcslen(dirCorrente);
      temp = (char *)malloc(size);
      wcstombs_s(NULL, temp, size+1, dirCorrente, size);
      return temp;
  }
  
  char* setCartellaCorrente(char* relative) {
      char *dirCorrente;
  
      if (strlen(relative)&gt;=5 &amp;&amp; relative[4] == ':') {
          dirCorrente = (char *)malloc(DEFAULT_BUFLEN);
          strcpy_s(dirCorrente, DEFAULT_BUFLEN, &amp;relative[3]);
      }
      else {
          dirCorrente = getCartellaCorrente();
          relative[2] = '\\';
          strcat_s(dirCorrente, DEFAULT_BUFLEN, &amp;relative[2]);
          printf("goode %s \n", dirCorrente);
      }
      //fixPathSlash(dirCorrente);
      printf("\n2: %s\n", dirCorrente);
      int i = _chdir(dirCorrente); //HERE IT STOPS
      printf("wtf: %d\n", i);
      free(dirCorrente);
      printf("boh\n");
      return getCartellaCorrente();
  }
  </code></pre>
  
  <p>It's my first question. Sorry if i missed some important information, i'll edit fast.</p>