10 ms·
You Can't Always Hash Pointers in C
- forrestthewoods 10y agoYou also can't test if a pointer points to an element in an array without undefined behavior. C++14 5.6/6, on subtracting pointers: "Unless both pointers point to elements of the same array object or one past the last element of the array object, the behavior is undefined." http://stackoverflow.com/questions/31774683/is-pointer-comparison-undefined-or-unspecified-behavior-in-c http://stackoverflow.com/questions/31774683/is-pointer-compa... I wish "undefined behavior" wasn't a thing in C/C++. It's not worth it. :(
- adrianratnapala 10y agoOr rather I wish the standard did not bend over backwards to allow every kind of aggressive optimisation that some compiler writer claims will increase speed of unoptimized code by 0.5%.
- thomasahle 10y agoIsn't that the point of C/C++? "Code should run as fast as the hardware allows" and "We allow you to do crazy things that probably won't be portable, if that's what you want". I wonder, if somebody created a language with C like semantics, like pointer arithmetic, but with a layer in between to ensure consistency and portability.. Would people want to use that, or would the semantics be considered less interesting, when they don't map directly to hardware?
- lmm 10y agoCorresponding directly to the hardware makes sense, sure. But what modern GCC (especially) does goes far beyond that. The intent of signed integer overflow being undefined is that it will be twos complement on a twos complement machine, not that I want half my code to not run if I had an overflow somewhere.
- Sacho 10y agoIf that was the intent, then overflow should have been classified as enumerated implementation-defined behavior, just like the bit representation of an integer type which already deals with those variations.
- caf 10y agoIf that had been the intent, it would have been specified as implementation-defined, not undefined. More likely, the intent was to also accomodate implementations that trapped on overflow.
- jjnoakes 10y agoImplementation-defined includes trapping on overflow.
- lmm 10y ago"Evaluates to an implementation-defined value" would not include that. I'm not sure if any of the usual definitions in the standard includes trapping and doesn't include arbitrary behaviour.
- jjnoakes 10y agoSure, but the standard need not say "Evaluates to an implementation-defined value". There are other wordings which use "implementation-defined" and would support trapping on overflow.
- tehrei 10y agoYeah but with those aggressive optimizations my code doesn't run at all.
- qb45 10y agoThis one is about portability, not optimizations. There are architectures where pointer isn't a simple int, due to things like segmentation, tagging or even possibly something as stupid as lack of sufficiently wide integer type. Heck, there were even C implementations for 36-bit machines, which had 36-bit registers and could only load/store 36-bit-sized and 36-bit-aligned chunks of memory. They packed 4 chars into such word (leaving 4 bits unused) and I don't know how they implemented char* but it must have been something totally mad and not reasonably castable to int or even int*.
- userbinator 10y agobut it must have been something totally mad and not reasonably castable to int or even int.* As long as you can impose an ordering on the elements in memory and thus derive a number for each one, it's possible to define the straightforward representation of a pointer. 4 chars per word is an easy case since you can just let char* be a number with the lowest 2 bits indicating the index within a single word, and the rest of the bits are the word-address. int* can be the same number with the lowest 2 bits always 0. If word addresses are smaller than 36 bits, then values with the higher bits set are invalid, and if they're larger, then use multiple words to hold them. Working with chars on such a machine is going to involve a lot of shifting and otherwise data movement, but there you go, a way to implement C pointers on such a machine.
- qb45 10y ago> int* can be the same number with the lowest 2 bits always 0. And now you have to right-shift int pointers on every dereference for some dubious benefit. It's easier and more efficient to make pointer arithmetic and casting painful.
- adrianratnapala 10y agoNo, you left-shift them on every cast. And is someone type-puns using a union, they get a thing four times samller than they might have expected. Stil it is totally well behaved in a hash.
- _yosefk 10y agoI think you can do that test by comparing pointers, you just can't subtract them. (The SO answer you link to also points out that comparing and subtracting are different, but I'm not sure that what I said follows.) In practice, almost all C and C++ programs depend on both implementation-defined and undefined behavior, and, modulo security implications, that's fine as long as you test the program properly after compiling with a new compiler.
- forrestthewoods 10y agoYou can test equality with a given element. But if you want to test "does this pointer to any element of that array" you can't. As this test would be: bool b = ptr - array_start < array_end - array_start But that first subtraction is undefined if ptr does not point to an element between start and end. Not that this is exactly a common operation or anything. But the fact that a seemingly simple and obvious test is undefined behavior is crazy imo.
- pygy_ 10y agoWhat about array_start <= ptr && ptr < array_end // or `<=` if the upper bound is inclusive Edit: well, for one it may not be thread safe, since it's not atomic, but neither is your example AFAIK.
- nightcracker 10y agoYour edit is pretty much irrelevant - it could be applied to literally any example code anywhere. Unless mentioned otherwise you should assume that all variables are thread-local.
- Sacho 10y agoEvaluating that expression is undefined behavior if ptr is outside the +1 bounds of the array. Check out the enumerated defined behavior in the (old C99, working draft) standard - http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf 6.5.8 Relational operators ...and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values... ... If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.
- Bromskloss 10y ago> I wish "undefined behavior" wasn't a thing in C/C++. It's not worth it. :( What do you suggest instead? Run-time checks?
- pjmlp 10y agoHave a proper defined behavior like most sane languages. The only reason UB exists was that when ANSI C came to be, the compiler writers and hardware vendors that provided C like compilers didn't want to give up on their semantics. So in order to please everyone, all the semantics that could not be defined on the standard became UB.
- unlinker 10y agoThat is untrue. UB exists because C is supposed to run on so many platforms there is no way to have a defined behaviour for all of them in that standard.
- wongarsu 10y agoMore importantly, C is not only supposed to run on many platforms (many programming languages do that), but also provide very low-level control on wide variety of platforms.
- pjmlp 10y agoWhich people keep forgetting is only available as implementation defined extensions, as such it is no longer ANSI C and any language compiler is free to have extensions.
- jjnoakes 10y agoThis is why implementation defined behavior exists. Undefined behavior though?
- pjmlp 10y agoI was already coding before C had any meaning outside UNIX.
- gpderetta 10y agoYou can do it by converting pointers to integers. No UB, but of course it is implementation defined.
- ArkyBeagle 10y agoUB is unfortunately inherent in the mission statement of 'C'/C++.
- gpderetta 10y agoSome motorola 68000 machines did automatically mask out some of the most significant bits of any pointers. This means that two pointers to the same object can have different representation. That did happen in practice as programmers used the highest bits to stuff metadata and relied on the automatic masking. That made things interesting when the platform wanted to increase the address space. And preventing this sort of backward compatiblity issue is the reason why AMD64 will trap if the unused bits of the address space are not all 1 or 0. Bottom line, the pointer to integer conversion should be specified by your platform ABI. Read it, then either refuse to support your program on platforms with insane ABIs or have a fallback path for them.
- vidarh 10y agoWasn't this the case with 68000 based designs in general? The CPU only had 24 address lines. I think it was first the 68020 that had a full 32 bit address bus And you're right, people absolutely did use it. On the Amiga I believe that Amiga BASIC (developed by Microsoft) was perhaps the most prominent example of Amiga applications that allegedly did this (only source I've found for this is a comment by a former Commodore employee - Dr Peter Kittel), amongst a massive amount of other problems. People did get it running on 68020+ systems, with a combination of patches and disabling fast ram, but it was pretty much forgotten from AmigaOS 2.x onwards anyway.
- gpderetta 10y ago"Wasn't this the case with 68000 based designs in general?" Possibly, I wasn't sure so I hedged :). And yes, I heard that the issue was mostly encountered on the Amiga.
- jsymolon 10y agoIn early Mac OSs, the memory management designs used the top byte for flags as those units didn't have a hardware MMU. System 7 was the first OS to support 32-bit.
- bnastic 10y ago
- tehrei 10y agoInteresting. What if I use memcpy and memcmp? As in, void foo(void *a, void *b) { char ca[sizeof(void*)]; char cb[sizeof(void*)]; memmove(ca, &a, sizeof(void*)); memmove(cb, &b, sizeof(void*)); assert((a == b) == (memcmp(ca, cb, sizeof(void*)) == 0)); }
- mikeash 10y agoThat doesn't help. Your assert can be false. Consider, for example, a 32-bit architecture which ignores the top 8 bits of the pointer (as was the case in the old 68000 Macs, as discussed elsewhere in these comments). Consider two pointers which differ only in a top bit, like 0x1000f000 and 0x0000f000. They will compare equal, but the underlying bytes extracted with your memmove call will differ. And this isn't just a historical curiosity. ARM64 can optionally ignore the top eight bits of its 64-bit pointers, for example.
- jks 10y agoIf you know that the strings are stored in the same table, couldn't you subtract from each pointer a pointer to the beginning of the table and hash the resulting offsets?
- caf 10y agoYes.
- svens_ 10y agoThat's probably true, however there's a small catch. Looking at the standard (no difference between C99/C11), chapter 6.5.6 ("additive operators"), point 9 defines the behavior of pointer subtraction: When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. However reading further: The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header. If the result is not representable in an object of that type, the behavior is undefined. Unlike the (u)intptr_t types, ptrdiff_t is not optional AFAIK. The way I understand it, you could still invoke UB if the implementation uses a very silly type for ptrdiff_t, though I didn't do further research on it. Still, using pointer difference makes this a lot safer and more portable. Especially on platforms with unusual memory models, where a pointer might not be just a single integer (e.g. segmented memory on x86). Also the operation is Theta(1), so it doesn't impact performance much.
- deleted 10y ago[deleted]
- gpderetta 10y agoThis remind me of a story. When Stephanov was implementing the STL, he needed a strict weak ordering among all pointers to implement things like std::map. Instead of wasting time arguing within the committee on wether operator< should have the required semantics, he simply added std::less as a primitive and default comparison for std::map. It is specified to call operator< for every T, except that for pointer it relies on unspecified compiler support for doing the right thing. On pretty much all implementations it simply calls operator< even for pointers.
- tehrei 10y agoOh, so then on C++ you can check if pointer-to-T p is within T a[sz]; by doing (a == p || std::less(a, p)) && (std::less(p, a + sz))
- gpderetta 10y agoPossibly not. The standard guarantees that less yields a total order for pointers. But the ordering itself is unspecified, and not even guaranteed to be consistent with operator< for pointers to elements of the same array.
- yoklov 10y agoI thought it was UB to use < on pointers outside of the same block of memory. e.g. your function is fine if the answer is true, but UB if the answer is false. I could be misremembering though, but I do know I'd always cast to uintptr_t for this.
- pjc50 10y agoAnother platform that doesn't have straightforward pointers: x86. 16-bit mode. Because of the segmentation system, if you wanted a fully general pointer to anywhere in the address space ("far") it had to be split into two registers. Greater speed could be achieved with "near" pointers, but only within a 64k segment. You could also very easily have non-identical pointers that pointed to the same memory location. Fragments of this mess survive in the Windows API, like Shelley's "vast and trunkless legs of stone": https://blogs.msdn.microsoft.com/oldnewthing/20031125-00/?p=41713 https://blogs.msdn.microsoft.com/oldnewthing/20031125-00/?p=...
- userbinator 10y agoI think the 8051 is more interesting - it's a Harvard architecture with at least 3 separate address spaces: http://www.keil.com/support/man/docs/c51/c51_le_ptrs.htm http://www.keil.com/support/man/docs/c51/c51_le_ptrs.htm http://www.keil.com/support/man/docs/c51/c51_le_ptrconversions.htm http://www.keil.com/support/man/docs/c51/c51_le_ptrconversio... Just like x86, it's likely that everyone interacts daily with a system containing at least 1 8051 core.
- svens_ 10y agoAs someone who did a lot of embedded development, I wouldn't exactly call it "more interesting". More like "that shit needs to die already". The biggest problem with those is, that modern compilers don't support it. Well, that is open-source compilers. IAR will happily sell you a license of their IDE for 2.4k$/seat. There is sdcc, but it's no comparison to a modern gcc or the commercial offerings. Unfortunately you're right though, 8051 processors are cheap and abundant. Chip makers use it as the go to architecture for any simple embedded processing requirements. It's slowly changing though, but ARM licensing costs are still much higher. Let's hope that in a decade or so they'll use RISC-V instead.
- vt240 10y agoYes, there is nothing more fun than moving a large 8051 embedded project from Keil to Tasking.
- js8 10y agoAnother platform: IBM zSeries has 24-bit and 31-bit addressing modes, so that means an address stored in a 32-bit register has some of the highest bits ignored when dereferenced. Especially in the past, people stored useful information into those bits, so again, the two pointers are not necessarily equal even though they can point to the same address.
- apaprocki 10y agoJust like the 48-bit addressing mode of the x86-64 chips most people reading this are using along with the storage of useful information in bits 48-64 (JS engines!).
- qb45 10y agoIf they store something there they have to mask it out before dereferencing the pointer. x86-64 doesn't ignore the topmost bits, if you set them wrong the CPU will throw an exception.
- cesarb 10y agoThe post mentions only the C standard; I wonder what POSIX says about it. And there are also the platform ABIs, which specify how a pointer is passed between functions. If you're in a platform in which the ABI doesn't allow arbitrarily setting unused bits, even a "security-conscious implementation" will have to leave them alone, since a pointer can be passed to a function written in a different language. This also means that the "map the same object at multiple virtual addresses" trick, in which the implementation flips bits within the pointer knowing there is always a valid alias mapping to it, is broken: suppose two pointers to within the same object are passed (perhaps at separate times) to code written in another language. From the point of view of the other language, they might not be pointing to the same object, even if they should (for instance an array and an element within it, the function might want to compute the offset). I also wonder how well does the "map the same object at multiple virtual addresses" trick work in architectures with VIVT caches, where both the index and the tag are virtual addresses. In these architectures, if you write through one mapping and want to access the same memory through another mapping, you have to flush the cache, otherwise you will have hard-to-debug problems if both mappings are in the cache at the same time.
- gpderetta 10y ago"I also wonder how well does the "map the same object at multiple virtual addresses" trick work in architectures with VIVT caches" Not well at all, unless the OS goes out of the way to do cache coloring. There is a reason that VIVT are today considered suboptimal.
- ausjke 10y agoVery insightful, never fully understand why pointers can't be cast to integers(not even to uintptr_r, intptr), what's the guidance here to avoid the casting?
- ArkyBeagle 10y agoYou'll need custom logic with in-depth knowledge of the mapping. In many cases the idiom mentions by "kazinator" above will often work - but not always: #define ptrToInt(x) ( ((char )x) - ( (char )0 ) ); ... and even that may require local tweaking.
- kazinator 10y ago> In other words, even in a conforming implementation, the same pointer might cast to two different integer values. If you're porting to that type of system, you will be keenly aware of this. The problem can be solved. On the Intel 8086, every address has 4096 ways of referring to it by some combination of segment:offset. A segment is 64 kilobytes wide, and the segment: part of the address is "paragraph" (16 byte block) aligned. 65536/16 = 4096. For instance address 0x1234 can be referenced as 0123:0004, or 0122:0014 and so on. However, there is a unique underlying address. A pointer value can be normalized (using nonportable code, of course) to use, say, the largest possible segment value and the smallest possible offset. The resulting value can then be hashed. Another way to deal with it on 8086 might be to use a "far" pointer, and calculate its offset from a "far" null pointer: (far char *) ptr - (far char *) 0; This should produce the physical address as an integer. So that is to say, the concept of hashing an address is sound; only using "pointer" to mean "address" is not maximally portable. An implementation of pointer hashing can be ported to such architectures by some nonportable code, if necessary. If you care about such portability, wrap the "pointer to integer address" logic in a function and implement that function as necessary.
- TazeTSchnitzel 10y agoA big problem for the Mill people has been getting LLVM to understand that pointers on the Mill do not behave like normal integers.
- Kristine1975 10y agoVideo about using clang/LLVM for the Mill here: https://www.youtube.com/watch?v=QyzlEYspqTI https://www.youtube.com/watch?v=QyzlEYspqTI