Enhance search index handling by returning an empty array for no results instead of throwing an error. Improve memory management in free_words function by checking for NULL before freeing. Update search_index to properly return NULL when no results are found.

This commit is contained in:
seb
2025-06-27 03:15:45 +02:00
parent 21f527ba46
commit 8474c77163
2 changed files with 13 additions and 5 deletions

View File

@@ -48,7 +48,9 @@ int split_into_words(const char *s,
// Free memory allocated for words
void free_words(char *storage) { /* simplified */
free(storage); /* single free, if any */
if (storage) { /* check for NULL */
free(storage); /* single free, if any */
}
}
// Calculate Levenshtein distance between two strings
@@ -105,7 +107,7 @@ float word_similarity(const char *word1, const char *word2) {
// Calculate similarity between query and target string
float calculate_similarity(const char *query, const char *target, float cutoff) {
// Split strings into words
char *query_buf, *target_buf;
char *query_buf = NULL, *target_buf = NULL;
char *query_words[MAX_WORDS], *target_words[MAX_WORDS];
int query_word_count = split_into_words(query, query_words, &query_buf);
@@ -304,6 +306,12 @@ SearchResult* search_index(SearchIndex* index, const char* query, float cutoff,
}
}
// If no results found, return NULL properly
if (*num_results == 0) {
free(temp_results);
return NULL;
}
// Sort results by similarity
qsort(temp_results, *num_results, sizeof(SearchResult), compare_results);