私はCに関数があり、2つの異なる場所(サイズは不明、かなり大きい可能性があります)から文字列を取得し、それらを1つの文字列に結合して返します。2つの文字列を出力するだけで正しい結果が得られますが、strcatを使用して文字列を結合しようとすると、5つのガベージ文字が表示され、結合された文字列の結果が表示されます。
誰かが私が間違っていることについていくつかのアドバイスがありますか?これが私がしていることを示すためのいくつかのサンプルコードです:
static int get_information(char** results)
{
size_t s1_length;
size_t s2_length;
/* DEBUGGING - Prints the correct string */
printf(get_string_1());
printf(get_string_2());
printf("\n");
/* Allocate memory for new string */
s1_length = strlen(get_string_1());
s2_length = strlen(get_string_2());
*results = malloc(sizeof(char) * (dir_length + file_length));
if(results == NULL)
return -1;
/* Combine the strings */
strcat(*results, get_string_1());
strcat(*results, get_string_2());
/* DEBUGGING - prints 5 garbage characters then the correct string */
printf(*results);
printf("\n");
return 0;
}