我想連接兩個字符串,所以我可以獲得文件路徑。不過,我在Valgrind的接收錯誤C Strcat valgrind錯誤
條件跳轉或移動依賴於未初始化的值(一個或多個)
我的代碼:
/**
* @brief Concatenate two strings to get file path
* @param firstP - First string
* @param secondP - Second string
* @return Returns the concatenated string
*/
char *getPathDir(char *firstP, char *secondP) {
char *new_str;
int stringSize = strlen(firstP)+strlen(secondP)+2;
if((new_str = malloc(stringSize)) != NULL){
new_str[0] = '\0';
strcat(new_str,firstP);
new_str[strlen(firstP)] = '/';
strcat(new_str,secondP);
} else {
perror("malloc");
cleanUp();
exit(EXIT_FAILURE);
}
return new_str;
}
'sprintf(new_str,「%s /%s」,firstP,secondP);'而不是。 'new_str [strlen(firstP)] ='/';'覆蓋字符串的最後一個空終止符。所以第二個'strcat'找不到正確字符串的結尾。 – BLUEPIXY
有很多更好的方法來做到這一點... strcat函數。請參閱:https://www.tutorialspoint.com/c_standard_library/c_function_strcat.htm或@BLUEPIXY建議太:) –
@BLUEPIXY我刪除if語句裏面的一切還有使用sprintf(new_str取代它, 「%S /%S」 ,firstP,secondP);它現在完美地工作。謝謝:) – Cows42