// strbrk を 3 回呼び出していますが、 != NULL かどうかを確認する必要があります。どうすればよいですか?
if(strpbrk(posfind,"<") != NULL ){
posfind =(char*)malloc(strlen(strpbrk(posfind,"<"))+strlen(posfind)*sizeof(char*));
posfind =strcat(strpbrk(posfind,"<"),posfind);
}
// strbrk を 3 回呼び出していますが、 != NULL かどうかを確認する必要があります。どうすればよいですか?
if(strpbrk(posfind,"<") != NULL ){
posfind =(char*)malloc(strlen(strpbrk(posfind,"<"))+strlen(posfind)*sizeof(char*));
posfind =strcat(strpbrk(posfind,"<"),posfind);
}
strcat
新しいメモリは割り当てられません。呼び出す前に、十分なスペースがあることを確認する必要があります。その呼び出しで部屋が足りなくなったようですstrcat
。したがって、*WHAM*です。
更新された例では、次のように、いくつかの一時変数を使用して、結果strpbrk(posfind, "<")
と新しいmallocされたメモリを格納します。
char* temp = strpbrk(posfind, "<");
char* newstring = NULL;
if (temp != NULL) {
// You had a typo with the size, and also don't forget to add a spot for the
// terminating null character
newstring = malloc((strlen(temp) + strlen(posfind) + 1) * sizeof(char));
newstring = strcpy(newstring, temp);
newstring = strcat(newstring, posfind);
posfind = newstring;
}
もちろん、すべての戻り値をチェックし、使用しなくなった割り当て済みメモリを解放する必要もあります。
strpbrk(posfind,"<")
に渡す null ポインターを返しますstrcat
。