我正在尝试编译和在Linux下用C编写的代码,并收到此错误消息:
glibc检测到malloc():内存损坏
我无法找出原因......
substring()只是通过给出起始索引和长度来返回原始字符串的一部分.例如substring("this is example",0,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;
}
Run Code Online (Sandbox Code Playgroud)
并且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,0,firstSpace);
printf("header …Run Code Online (Sandbox Code Playgroud)