Chan Rasjid wrote:Code: Select all
// 1) bug
hash = malloc(hash_size + 63) & ~63;
// 2) should be -
hash = (malloc(hash_size + 64) & ~63) + 64;
I retrieved the line by Bob Hyatt from an old post. I think it has a bug. If 'hash' from 1) is assigned to the transposition table, it means it overwrites memory beyond the original starting address from malloc().
I have some sort of segmentation fault, etc when the original pointer from malloc() was free()'ed - main() did not exit with a clear status 0; 2) solves the problem.
Rasjid
How would this fail? You malloc N+63 bytes, then force the rightmost 6 bits to zero with the and. Suppose the original hash address is aligned at address 1024 (x"00000400') You get hash = 0x400 + 0x3f, or 0x43f, then you and with 0xffffffc0, binary:
1111 1111 1100 0000
0000 0100 0011 1111
which is
0000 0100 0000 0000
which looks perfect (I did the above using rightmost 16 bits only.
Suppose you get hash = 0x418. Add the 3f to it and you get 0x457
1111 1111 1100 0000
0000 0100 0101 0111
which is
0000 0100 0100 0000
which looks right to me.
Note that when I did the original malloc (assume I asked for 64 bytes total) and got 400, I grabbed addresses 0x400 - 0x400 + 64 + 63 or 0x400 - 0x47f.
Any address between start and start+63 (I asked for 64 bytes) certainly fits in that range and gives 0x400 - 0x43f which is inside the 63-byte larger block.
For the second example, which returned address 0x418. I asked for 64 + 63 extra bytes, which is 0x7f. So I got addresses 0x418 - 0x497 and I am going to use addresses 0x440 - 0x47f.
I am not sure what you think is wrong, or what I am overlooking if something really is wrong...