C out-of-bound pointer question
Simias
simias.n at gmail.com
Thu Nov 15 22:46:10 PST 2007
deeptech71 at gmail.com writes:
> int x[N];
>
> Values in x[] are (rand()%10)+268435410, aka 268435410..268435419.
> The algorith counts each individual value.
>
> // v1.0 uses if( x[n] == ___ )'s
>
> // v2.0:
> int k[268435420] = {0}; // k uses almost 1GB of memory
> for (n = 0; n < N; n++) {
> k[ x[n] ]++;
> }
>
> // v2.1:
> int k[10] = {0};
> int* p = k-268435410;
> for (n = 0; n < N; n++) {
> p[ x[n] ]++;
> }
>
> The values in x[] are guaranteed, so k[ x[n]-268435410 ] are k[0] to
> k[9], but is *((k-268435410)+26843541_) safe? (as long as I do no
> dereference such out-of-bound memory region)
> _______________________________________________
> freebsd-chat at freebsd.org mailing list
> http://lists.freebsd.org/mailman/listinfo/freebsd-chat
> To unsubscribe, send any mail to "freebsd-chat-unsubscribe at freebsd.org"
>
I don't really understand the problem,
*((k-268435410)+26843541x) <=> *(k + x) <=> k[x], so as long as x
belongs to [0; 10[ there's no out of bound issue.
However, note that in "int* p = k-268435410;", if the address of k is
inferior to 268435410, p will old a negative address. This won't be a
problem in x86 and most other architectures I'm aware of, but I'm not
sure this behaviour is defined by the C standard.
(also, I'd use macros, like #define WHATEVER 268435410, it'll make the
code way more readable)
--
Simias
More information about the freebsd-chat
mailing list