glibc检测到malloc():C中的内存损坏

我正在尝试编译和在 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 …

任何提示都将不胜感激,谢谢!

解决方法

newString[x] = '\0';

此时x等于length,这意味着你要在分配的内存末尾写入1个字符.您需要为另外一个角色分配空间.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...