linux malloc内存检测,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 …

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值