简体   繁体   中英

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.

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. 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). This is a certain way to run your system out of memory even before you start allocating HashEntry objects themselves!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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