@@ -61,6 +61,8 @@ namespace hnswlib {
6161 maxlevel_ = -1 ;
6262
6363 linkLists_ = (char **) malloc (sizeof (void *) * max_elements_);
64+ if (linkLists_ == nullptr )
65+ throw std::runtime_error (" Not enough memory: HierarchicalNSW failed to allocate linklists" );
6466 size_links_per_element_ = maxM_ * sizeof (tableint) + sizeof (linklistsizeint);
6567 mult_ = 1 / log (1.0 * M_);
6668 revSize_ = 1.0 / mult_;
@@ -546,12 +548,16 @@ namespace hnswlib {
546548
547549 // Reallocate base layer
548550 char * data_level0_memory_new = (char *) malloc (new_max_elements * size_data_per_element_);
551+ if (data_level0_memory_new == nullptr )
552+ throw std::runtime_error (" Not enough memory: resizeIndex failed to allocate base layer" );
549553 memcpy (data_level0_memory_new, data_level0_memory_,cur_element_count * size_data_per_element_);
550554 free (data_level0_memory_);
551555 data_level0_memory_=data_level0_memory_new;
552556
553557 // Reallocate all other layers
554558 char ** linkLists_new = (char **) malloc (sizeof (void *) * new_max_elements);
559+ if (linkLists_new == nullptr )
560+ throw std::runtime_error (" Not enough memory: resizeIndex failed to allocate other layers" );
555561 memcpy (linkLists_new, linkLists_,cur_element_count * sizeof (void *));
556562 free (linkLists_);
557563 linkLists_=linkLists_new;
@@ -659,6 +665,8 @@ namespace hnswlib {
659665
660666
661667 data_level0_memory_ = (char *) malloc (max_elements * size_data_per_element_);
668+ if (data_level0_memory_ == nullptr )
669+ throw std::runtime_error (" Not enough memory: loadIndex failed to allocate level0" );
662670 input.read (data_level0_memory_, cur_element_count * size_data_per_element_);
663671
664672
@@ -675,6 +683,8 @@ namespace hnswlib {
675683
676684
677685 linkLists_ = (char **) malloc (sizeof (void *) * max_elements);
686+ if (linkLists_ == nullptr )
687+ throw std::runtime_error (" Not enough memory: loadIndex failed to allocate linklists" );
678688 element_levels_ = std::vector<int >(max_elements);
679689 revSize_ = 1.0 / mult_;
680690 ef_ = 10 ;
@@ -689,6 +699,8 @@ namespace hnswlib {
689699 } else {
690700 element_levels_[i] = linkListSize / size_links_per_element_;
691701 linkLists_[i] = (char *) malloc (linkListSize);
702+ if (linkLists_[i] == nullptr )
703+ throw std::runtime_error (" Not enough memory: loadIndex failed to allocate linklist" );
692704 input.read (linkLists_[i], linkListSize);
693705 }
694706 }
@@ -828,6 +840,8 @@ namespace hnswlib {
828840
829841 if (curlevel) {
830842 linkLists_[cur_c] = (char *) malloc (size_links_per_element_ * curlevel + 1 );
843+ if (linkLists_[cur_c] == nullptr )
844+ throw std::runtime_error (" Not enough memory: addPoint failed to allocate linklist" );
831845 memset (linkLists_[cur_c], 0 , size_links_per_element_ * curlevel + 1 );
832846 }
833847
0 commit comments