Linux で C で記述されたコードをコンパイルおよびコーディングしようとすると、次のエラー メッセージが表示されます。
glibc が malloc() を検出しました: メモリ破損
そして、私はその理由を見つけることができません...
substring() は、開始インデックスと長さを指定して、元の文字列の一部を返すだけです。例: substring("これは例です",0,4) = "これ";
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,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 は通常 stdin で、「メッセージ ID を送信する」の形式を持ち、メッセージが 12 文字の長さの場合にエラーが発生します... 例: 「このメッセージ 4 を送信する」、「このメッセージ」は cmd です12文字の長さがあるため、エラーが発生します! 他の長さでも問題なく動作します.3、4、24を試しました...
ヒントをいただければ幸いです。ありがとうございます。