Re:Massacring C Pointers (2018)
by enriquto on Saturday September 05, 2020 @10:25AM
(#24383752)
Sure. When you study physics you first learn Newtonian gravitation; and later, once you really master it, you learn that it is actually false and proceed to learn general relativity. In a similar way, it is very useful for people who learn C to start with the idea that "a pointer is an int". Then, they can discover that pointers are not really ints, but not before they have mastered working with pointers as if they were ints.
[ Parent
| on HN ]
Could you explain (or link to a good resource about) what pointers really are? I'm surprised that they aren't just ints that point to the address of a variable.
In all modern implementations that I know of, pointers are effectively ints. But the formal definition of the C language takes great care in not saying that, allowing for implementation to chose how to implement pointers. In some older systems, for example in 16-bit MS-DOS with "high memory", pointers were not really ints, but pairs of ints (called the segment and the offset, if I recall correctly) whose mapping to memory positions was overlapping, i.e., non unique, you could have very different representations for the same memory position. I guess the gcc port to MSDOS by DJ Delorie had to deal with these issues somehow.
But it is possible to imagine completely exotic CPU architectures, where there is a separate type of register that can only be used for pointers and it is impossible to convert to int; you could still write C compilers for that architecture and be 100% conforming to the standard.
If I remember 16 bit C compilers let you choose a couple of different memory models. I remember 3, data and code fits in 16bits. data is 16 bits and code is segment and offset. And both pointers are segment and offset. I think there were more, especially for systems with 'high memory'
Most processors a pointer just gets stuffed into a register and then that's used by a assembly instruction to read/write a memory location. But it's certainly possible to have systems where it's not so simple.
They are variables that store an address. Usually they are of integer-ish thing internally, but this is in no way required, just like C has no need to run on a machine with linear memory. You could have a variable to memory hash table backing all your objects, for example, with a pointer that is a bucket or something.
This is the kind of thing that you need a significant other to straighten out.
"Hey!"
(smacks on head)
"It's an int that points to a variable."
"Now get off the computer and take out the trash without talking about garbage collection!"
"but it could be an int32_t and sometimes..."
(smack)
Re:Massacring C Pointers (2018)
by steveklabnik on Saturday September 05, 2020 @06:13PM
(#24387275)
This is what you want to read: https://blog.regehr.org/archives/1621