Hacker News new | ask | show | jobs
by Animats 3465 days ago
Yes. This only works for arrays on the stack, at best. It assumes that arrays are placed on the stack in the order of declaration, which is not a requirement of the C standard and may differ between compilers.

Unless you're writing a buffer overflow exploit, in which case you need to know exactly what's on the stack and where, this isn't a good way to program.

Update: misread the article; thought he was differencing with the beginning of the next array.

2 comments

I don't see how the code assumes anything about the placement of the array. Indeed, it works just fine for static arrays:

    $ cat test.c
    #include <stdio.h>
    
    int arr[5];
    
    int main(int argc, char *argv[]) {
    	printf("%lu, %ld\n", sizeof(arr) / sizeof(*arr), (&arr)[1] - arr);
    }
    
    $ gcc test.c && ./a.out
    5, 5
Not saying it's "a good way to program" - it's needlessly obfuscated compared to the standard sizeof alternative. But it doesn't rely on anything tricky.
> It assumes that arrays are placed on the stack in the order of declaration

I am not sure it is the case here. The code uses only one array, how can it assume the order of arrays?