3 ms·
C array access is (not totally accurate) replaceable with pointer arithmetic and dereferencing. So array[-1] is the same as *(array - 1). So long as your progra
by Jtsummers 5y ago
C array access is (not totally accurate) replaceable with pointer arithmetic and dereferencing. So array[-1] is the same as *(array - 1). So long as your program controls that bit of memory, it is a safe operation (you won't be accessing memory outside of whatever the OS/runtime allocated to your process). For instance, if you have this struct definition:
typedef struct {
int a;
int b[10];
} foo;
Then the following will (likely) work:
foo f;
f.a = -1;
printf("%d\n", f.b[-1]); // => -1
In fact, the following also works:
f.b[0] = 10;
printf("%d\n",(&(f.a))[1]); // => 10
C is very flexible in allowing you to do what you want with addresses (once obtained). But yes, if you don't control it then it is likely going to be garbage data.
- scroot 5y ago> C array access is (not totally accurate) replaceable with pointer arithmetic and dereferencing. So array[-1] is the same as *(array - 1). Thanks, that part is clear. I guess in the Piumarta paper, he's assuming all of these objects are contiguous in memory? Because the vtable pointer is always to [-1] but it's not specified in any given struct...
- Jtsummers 5y agoI also missed the specific solution the first time, but see figure 10 on page 6 (in section 3.1, the pages aren't numbered). It's doing a variant of what I described, in this case they're doing this (copied the document, pseudocode): function vtable_allocate(self, size) = let object = allocateMemory(PointerSize + size) object := object + PointerSize object[-1] := self return object This will guarantee that the memory is contiguous and properly allocated to the process so it's not using garbage data.