djb2 by Dan Bernstein for c++

ratkke picture ratkke · Nov 10, 2013 · Viewed 8.1k times · Source

I've tried to translate djb2 hash function from c-code

unsigned long
hash(unsigned char *str)
{
    unsigned long hash = 5381;
    int c;

    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}

to c++ code, but i have segmentation fault.

int hf(std::string s){
    unsigned long hash = 5381;
    char c;
    for(int i=0; i<s.size(); i++){
        c=s[i++];
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
    }
    return hash;

Where is my mistake? Thanks in advance

Answer

rightfold picture rightfold · Nov 10, 2013

You want s[i], not s[i++]. Even better would be to use range-based for.

int hf(std::string const& s) {
    unsigned long hash = 5381;
    for (auto c : s) {
        hash = (hash << 5) + hash + c; /* hash * 33 + c */
    }
    return hash;
}