in
concatena(input1, input2, output);
printf("%s\n", output);
значение output не изменяется concatena , поэтому вы печатаете неинициализированный символ * => сбой или любое другое неопределенное поведение
вам нужно сделать вывод выходной переменной, поэтому void concatena(char *input1, char *input2, char **output)
и т. Д. Вот так:
int main(void){
char *input1, *input2, *output;
input1 = "sdaeteruiop";
input2 = "eiyearteoiana";
concatena(input1, input2, &output);
printf("%s\n", output);
free(output);
return 0;
}
void concatena(char *input1, char *input2, char **output){
int num_cons1 = 0, num_cons2 = 0, dim_input1, dim_input2;
conta_consonanti(input1, &num_cons1);
conta_consonanti(input2, &num_cons2);
if(num_cons1 < num_cons2){
dim_input1 = strlen(input1) + strlen(input2);
*output = malloc(dim_input1 + 1);
strcpy(*output, input1);
strcat(*output, input2);
}else {
dim_input2 = strlen(input2) + strlen(input1);
*output = malloc(dim_input2 + 1);
strcpy(*output, input2);
strcat(*output, input1);
}
}
Я также исправил ваш malloc, вы пропустили 1 символ для нулевого терминатора
предупреждение, если вывод num_cons2 == num_cons1
* не установлен, и вы по-прежнему печатаете его без инициализации, вам нужно установить его в NULL и проверить этот случай перед его печатью, или, более вероятно, заменить else if(num_cons2 < num_cons1)
на else
(вот чтоЯ делал это выше)
обратите внимание, что dim_input1
и dim_input2
имеют одинаковое значение, их бесполезно различать
, и первый вызов copy_string
можно заменить на strcpy
а второй - strcat
, за исключением того, что copy_string
пропущено, чтобы добавить окончательный нулевой символ .Я исключил использование copy_string
, предупреждающее, что объявление void concatena(char *, char *, char *);
должно быть обновлено до void concatena(char *, char *, char **);
Выполнение:
eiyearteoianasdaeteruiop
Под valgrind:
pi@raspberrypi:~ $ valgrind ./a.out
==15629== Memcheck, a memory error detector
==15629== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==15629== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==15629== Command: ./a.out
==15629==
eiyearteoianasdaeteruiop
==15629==
==15629== HEAP SUMMARY:
==15629== in use at exit: 0 bytes in 0 blocks
==15629== total heap usage: 2 allocs, 2 frees, 1,049 bytes allocated
==15629==
==15629== All heap blocks were freed -- no leaks are possible
==15629==
==15629== For counts of detected and suppressed errors, rerun with: -v
==15629== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)