Question

I compiled the program with -Criot -gl flags and instead of 1 I get a lot of results to my surpise (in fact, I was looking for fix a 216 error). The first is with the below code that's a simple hashing function. I have no idea how to fix this.

function HashStr(s : string) : integer;
var h : integer;
var c : char;
begin
   h := 0;
   for c in s do
      h := ord(c) + 31 * h; { This is the line of error }
   HashStr := h;
end;

How can this be out of ranges?

Was it helpful?

Solution

Easily, say you have a string "zzzzzzzzzzz". Ord(c) wil be 122, so the sequence is

 H = 122 + (31* 0 ) = 122
 H = 122 +(31*122) = 3902
 H = 122 +(31*3902) = 121146

Which exceeds the 32767 limit for 16 bit ints, if it's a 32 but int, it won't take many more iterations to exceed that limit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top