微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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个字符.您需要为另外一个角色分配空间.

原文地址:https://www.jb51.cc/c/116996.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐