mirror of
https://github.com/theoludwig/programming-challenges.git
synced 2025-05-18 12:02:53 +02:00
fix(solutions): fix: more memory issues thanks to -fsanitize=address flag with gcc
This commit is contained in:
@ -5,34 +5,21 @@
|
||||
|
||||
#include "input.h"
|
||||
|
||||
char *swap(char *string, size_t index_from, size_t index_target) {
|
||||
size_t string_length = strlen(string);
|
||||
char *result = malloc(sizeof(char *) * (string_length));
|
||||
for (size_t index = 0; index < string_length; index++) {
|
||||
if (index == index_from) {
|
||||
result[index] = string[index_target];
|
||||
} else if (index == index_target) {
|
||||
result[index] = string[index_from];
|
||||
} else {
|
||||
result[index] = string[index];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
void swap(char *string, size_t index_from, size_t index_target) {
|
||||
char temporary = string[index_from];
|
||||
string[index_from] = string[index_target];
|
||||
string[index_target] = temporary;
|
||||
}
|
||||
|
||||
void heap_algorithm(unsigned long number_of_elements_to_operate, char *string) {
|
||||
void heap_algorithm(char *string, size_t number_of_elements_to_operate) {
|
||||
if (number_of_elements_to_operate == 1) {
|
||||
printf("%s\n", string);
|
||||
} else {
|
||||
heap_algorithm(number_of_elements_to_operate - 1, string);
|
||||
heap_algorithm(string, number_of_elements_to_operate - 1);
|
||||
for (size_t index = 0; index < number_of_elements_to_operate - 1; index++) {
|
||||
bool is_even = number_of_elements_to_operate % 2 == 0;
|
||||
if (!is_even) {
|
||||
string = swap(string, index, number_of_elements_to_operate - 1);
|
||||
} else {
|
||||
string = swap(string, 0, number_of_elements_to_operate - 1);
|
||||
}
|
||||
heap_algorithm(number_of_elements_to_operate - 1, string);
|
||||
swap(string, is_even ? index : 0, number_of_elements_to_operate - 1);
|
||||
heap_algorithm(string, number_of_elements_to_operate - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -40,6 +27,7 @@ void heap_algorithm(unsigned long number_of_elements_to_operate, char *string) {
|
||||
int main() {
|
||||
char *string = input();
|
||||
size_t string_length = strlen(string);
|
||||
heap_algorithm(string_length, string);
|
||||
heap_algorithm(string, string_length);
|
||||
free(string);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
Reference in New Issue
Block a user