diff --git a/similarity_search.c b/similarity_search.c index 6dc750a..40b3d21 100644 --- a/similarity_search.c +++ b/similarity_search.c @@ -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); diff --git a/similarity_search_addon.cc b/similarity_search_addon.cc index 40aa2f4..8cb0787 100644 --- a/similarity_search_addon.cc +++ b/similarity_search_addon.cc @@ -129,9 +129,9 @@ Napi::Value SearchIndexWrapper::Search(const Napi::CallbackInfo& info) { int num_results = 0; SearchResult* results = search_index(this->index_, query.c_str(), cutoff, &num_results); - if (!results) { - Napi::Error::New(env, "Search failed").ThrowAsJavaScriptException(); - return env.Null(); + // If no results found, return empty array instead of throwing error + if (!results || num_results == 0) { + return Napi::Array::New(env, 0); } Napi::Array result_array = Napi::Array::New(env, num_results);