title: glibc detected malloc(): memory corruption in C
body: <p>I am trying to compile and code written in C under linux, and got this error message:</p>
  
  <blockquote>
    <p>glibc detected  malloc(): memory corruption</p>
  </blockquote>
  
  <p>and I cannot find out why...</p>
  
  <p>the substring() just return you part of the original string by giving the starting index and length.  e.g. substring("this is example",0,4) = "this";</p>
  
  <pre><code>char *substring(char* str, int start, int length) {
      char *newString = (char *)malloc(length * sizeof(char));
      int i, x = 0;
      int end=start+length-1;
      for(i = start ; i &lt;= end; i++){
          newString[x++] = str[i];
      }
      newString[x] = '\0';
      return newString;
  }
  </code></pre>
  
  <p>and the getCharIndexFirst() just returns the index of first occurance of the specified char
  the getCharIndexLast() just returns the index of last occurance of the specified char</p>
  
  <p>and below is the main function:</p>
  
  <pre><code>//consoleCommand has the form of 'send MESSAGE ID', has the value from stdin
  
  int firstSpace = getCharIndexFirst(consoleCommand,' ');
  int lastSpace = getCharIndexLast(consoleCommand,' ');
  int len = strlen(consoleCommand);
  
  char *header = substring(consoleCommand,0,firstSpace);
  printf("header is: %s\n",header);
  char *cmd = substring(consoleCommand,firstSpace+1,lastSpace-firstSpace-1);
  printf("command is: %s\n",cmd); // the code only runs up to here and output the error..
  char *socketstr = substring(consoleCommand,lastSpace+1,len-lastSpace-1);
  printf("socket is: %s\n",socketstr);
  </code></pre>
  
  <p><strong>Here is more info: the consoleCommand is usually the stdin, has the form of 'send MESSAGE ID', the error occurs when the MESSAGE is 12 char long...
  e.g. 'send this message 4', 'this message' is the cmd and has length of 12 chars, this gives me error! 
  and it works fine for any other lengths, i have tried 3, 4, 24...</strong></p>
  
  <p>Any hint will be appreciated, THANKS!</p>