title: C++: glibc detected corrupted double-linked list: 0x08f8f148
body: <p>I'm writing a program which needs to parse the PATH environment variable at a delimiter ":". Everything seems to be working properly until function chop tries to return the array. I then receive the following error:  "glibc detected  ./a.out: corrupted double-linked list: 0x08f8f148". I use the chop to also parse user input and it works properly. Any help is greatly appreciated.</p>
  
  <pre><code>//Parse environment variable
      char const* pPath = getenv("PATH");
      if (pPath == NULL){;}
      else{
          string ePath(pPath);
          envp = chop(ePath,':');
      }
  
  char **chop(string s, char c){
      int i, j, k, len, words = 0;
      len = s.length();
      //determine # of words
      for(i=0;i&lt;len+1;i++){
          if(s[i] == c || s[i] == '\0'){words++;}
      }
      char **array;
      string x;
      //allocate memory for char pointers
      if((array=(char**)malloc((words+1)*sizeof(char*))) == NULL){return NULL;}
      array[0] = &amp;x[0];
      i = 0; k = 0;
      //split string on char c
      for(j = 1; j &lt; (words+1); j++,k++,i++){
          //read in characters until delimiter
          while (s[k] != c &amp;&amp; s[k] != '\0'){
  
              x[i] = s[k];
              i++; k++;
          }
          x[i] = '\0';
          array[j] = &amp;x[i+1];
      }
      array[j] = 0;
      return array;   
  }
  </code></pre>