glibc检测到malloc():C中的内存损坏 [英] glibc detected malloc(): memory corruption in C

查看:66
本文介绍了glibc检测到malloc():C中的内存损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Linux下用C编写代码并得到此错误消息:

I am trying to compile and code written in C under linux, and got this error message:

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

glibc detected malloc(): memory corruption

我不知道为什么...

and I cannot find out why...

substring()只是通过提供起始索引和长度来返回原始字符串的一部分.例如substring("this is example",0,4)="this";

the substring() just return you part of the original string by giving the starting index and length. e.g. 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;
}

和getCharIndexFirst()仅返回指定字符首次出现的索引getCharIndexLast()仅返回指定字符最后一次出现的索引

and the getCharIndexFirst() just returns the index of first occurance of the specified char the getCharIndexLast() just returns the index of last occurance of the specified 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 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通常是标准输入,形式为发送消息ID",当消息长度为12个字符时会发生错误...例如发送此消息4",此消息"为cmd,长度为12个字符,这给了我错误!它适用于任何其他长度,我已经尝试过3、4、24 ...

感谢任何提示,谢谢!

推荐答案

newString[x] = '\0';

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

At this point x is equal to length, which means you're writing 1 character beyond the end of the memory you allocated. You need to allocate space for one more character.

这篇关于glibc检测到malloc():C中的内存损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆