Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 16 Nov 2007 07:31:06 +0100
From:      Simias <simias.n@gmail.com>
To:        deeptech71@gmail.com
Cc:        freebsd-chat@freebsd.org
Subject:   Re: C out-of-bound pointer question
Message-ID:  <864pfmvh05.fsf@simias.hd.free.fr>
In-Reply-To: <473D344C.1080805@gmail.com> (deeptech's message of "Fri, 16 Nov 2007 07:10:20 %2B0100")
References:  <473D344C.1080805@gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
deeptech71@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@freebsd.org mailing list
> http://lists.freebsd.org/mailman/listinfo/freebsd-chat
> To unsubscribe, send any mail to "freebsd-chat-unsubscribe@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



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?864pfmvh05.fsf>