简体   繁体   English

如何在以下代码中处理内存分配错误?

[英]How can I handle memory allocation errors in the following code?

const unsigned long long TABLE_SIZE = (1ULL << 34);

class HashMap {
private:
      HashEntry** table;
public:
      HashMap() {
            table = new HashEntry*[TABLE_SIZE]; 
            for (int i = 0; i < TABLE_SIZE; i++)
                  table[i] = NULL;
      }
};

The above code on compilation throws the following exception: "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc" whereas the code below throws no errors or warnings and compiles properly. 上面的编译代码将引发以下异常:“在引发'std :: bad_alloc'what():std :: bad_alloc实例之后调用终止”,而下面的代码则不引发错误或警告并正确编译。

const unsigned long long TABLE_SIZE = 65536;

class HashMap {
private:
      HashEntry** table;
public:
      HashMap() {
            table = new HashEntry*[TABLE_SIZE]; 
            for (int i = 0; i < TABLE_SIZE; i++)
                  table[i] = NULL;
      }
};

I believe the "bad_alloc" exception is being thrown because the system ran out of memory. 我相信由于系统内存不足而引发了“ bad_alloc”异常。 I would like to know how to get around this problem to get this code to work. 我想知道如何解决此问题以使此代码正常工作。

Depending on the size of a pointer, your first block of code is requesting 128 gigabytes of contiguous memory (I am assuming 64-bit addresses, because you cannot even address that many bytes in a 32-bit address space). 根据指针的大小,您的第一段代码将请求128 GB的连续内存(我假设使用64位地址,因为您甚至无法在32位地址空间中寻址那么多字节)。 This is a certain way to run your system out of memory even before you start allocating HashEntry objects themselves! 这是在您开始分配HashEntry对象本身之前就将系统用尽内存的某种方法!

Fortunately, hash tables commonly require a lot fewer buckets than that: hash code gets translated to the actual range of valid bucket indexes with modulo % operator, and then a collision resolution algorithm is used to deal with multiple hash values being "mapped" to the same bucket. 幸运的是,哈希表通常需要的存储桶要少得多:使用%运算符将哈希码转换为有效存储桶索引的实际范围,然后使用冲突解决算法来处理多个“映射”到哈希值的哈希值。同一桶。 This approach lets you "fold" a large space of possible hash values onto a much smaller space of valid hash indexes. 这种方法可以让你“折叠”可能哈希值的空间大到有效的哈希索引的一个更小的空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM