我正在尝试编译和在
Linux下用C编写的代码,并收到此错误消息:
glibc detected malloc(): memory corruption
我无法找出原因……
substring()只是通过给出起始索引和长度来返回原始字符串的一部分.例如substring(“this is example”,4)=“this”;
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 <= end; i++){
newString[x++] = str[i];
}
newString[x] = '\0';
return newString;
}
getCharIndexFirst()只返回指定char的第一次出现的索引
getCharIndexLast()只返回指定char的最后一次出现的索引
以下是主要功能:
//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,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);
这里有更多信息:consoleCommand通常是stdin,具有’发送MESSAGE ID’的形式,当MESSAGE为12个字符长时发生错误…
例如’发送此消息4′,’此消息’是cmd并且长度为12个字符,这给了我错误!
它适用于任何其他长度,我尝试过3,4,24 …
任何提示都将不胜感激,谢谢!