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

glibc检测到malloc():C中的内存损坏,c,pointers,memory,glibc,memory-corruption,C,Pointers,Memory,Glibc,Memory Corruption,我正在尝试在linux下用C编写编译和代码,并收到以下错误消息: glibc检测到malloc():内存损坏 我不知道为什么 substring()通过给出起始索引和长度,只返回原始字符串的一部分。e、 g.子字符串(“这是示例”,0,4)=“这” 这里有更多信息:控制台命令通常是stdin,具有“发送消息ID”的形式,当消息长度为12个字符时会发生错误。。。 e、 g.“发送此消息4”,“此消息”是cmd,长度为12个字符,这给了我错误! 对于任何其他长度,它都可以正常工作,我已经尝试了3、4

我正在尝试在linux下用C编写编译和代码,并收到以下错误消息:

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

我不知道为什么

substring()通过给出起始索引和长度,只返回原始字符串的一部分。e、 g.子字符串(“这是示例”,0,4)=“这”

这里有更多信息:控制台命令通常是stdin,具有“发送消息ID”的形式,当消息长度为12个字符时会发生错误。。。 e、 g.“发送此消息4”,“此消息”是cmd,长度为12个字符,这给了我错误! 对于任何其他长度,它都可以正常工作,我已经尝试了3、4、24…


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

您没有为终止的
'\0'
字符分配任何空间,因此您的分配溢出以写入此字符。您还需要在分配中计算此字符:

char *newString = (char *)malloc((length + 1) * sizeof(char));

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

学习使用和编译所有警告和调试ingo(例如,
gcc-Wall-g
)。使用
gdb
调试器。@hughsizeof(char)==1,没有意义。找到这类bug的工具是Valgrind——它会直接指向bug。如果你使用的是arm机器,尤其是arm64,Valgrind不够最新,因为它试图了解每个操作码。3.13了解arm,但不了解arm64。GDB经常在回溯上给出无意义的东西,甚至使用-g编译。在unicode和宽字符时代,假设sizeof(char)始终为1是不安全的。但是是的,终止'\0'总是需要1字节。@AlanCorey char被标准强制为单字节。Unicode与此无关。
//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);
char *newString = (char *)malloc((length + 1) * sizeof(char));
newString[x] = '\0';