There's no bounds testing in hget(): some valid sequences of operations will cause buffer overflows. For example, this should segfault: int (**table)[2] = hnew(); for (int j=0; j The problem is, the probing function doesn't wrap (the "t += h" part), so if you have have several colliding keys, it will probe for them past the end of the table.
Yeah... it’s easy to write small code that doesn’t work.
15-line hash table in C
31–40 of 104 posts
Re: 15-line hash table in C
#32Is this some common style? int (**hnew()) I've never seen parens used like that. Usually it's: int **hnew()
Re: 15-line hash table in C
#33Re: 15-line hash table in C
#34People understand that the compiler/executable doesn't run any faster the less newlines there are, right? This is cute, but as others have pointed out it, it isn't really a correct implementation of a hash table. Also, it wouldn't pass a code review anywhere I've ever worked.
Well that's the whole point, right? This is clearly written for fun, it's not production code, it's not supposed to pass a code review. It's just supposed to be cool and interesting, and a challenge for the author.
Re: 15-line hash table in C
#35Re: 15-line hash table in C
#36Is learning how to create a hash table necessary for a software engineer?
Re: 15-line hash table in C
#37People understand that the compiler/executable doesn't run any faster the less newlines there are, right? This is cute, but as others have pointed out it, it isn't really a correct implementation of a hash table. Also, it wouldn't pass a code review anywhere I've ever worked.
> This is cute Well that's the whole point, right? This is clearly written for fun, it's not production code, it's not supposed to pass a code review. It's just supposed to be cool and interesting, and a challenge for the author.
[0] - http://lelandbatey.com/posts/2014/09/binary-tree-printer/
Re: 15-line hash table in C
#38// corrected overflow hget
for (int k2=k,o=0; t[k&(SIZE-1)] && **t[k&(SIZE-1)] != k2 && o
// hset now allows overwrite for (int (**a)[2] = hget(t, k); a && (*a || (*a=malloc(sizeof(**t)))); (**a)[0]=k,(**a)[1]=v,a=0);Re: 15-line hash table in C
#39If you rewrote this exact logic in Python it would be longer, because then the code would actually be readable. However, fortunately it's just two chars: {}
Re: 15-line hash table in C
#40C++ wins again.