Re: Segmentation Fault
- From: "Herbert Rosenau" <os2guy@xxxxxxxxxxxxx>
- Date: Fri, 4 Sep 2009 16:37:04 +0000 (UTC)
On Tue, 1 Sep 2009 22:08:16 UTC, Nobody <nobody@xxxxxxxxxxx> wrote:
On Tue, 01 Sep 2009 22:57:48 +0100, Rahul wrote:
I believe my code is correct and caches all results in an Array for
efficiency (only look up is needed). But it generates a Segmentation Fault
everytime I run it.
Can anyone see what the problem is?
static bool squares[INT_MAX]; // automatically initialized to 0, no
You shouldn't assume that you will be able to allocate an array this
large (on a 32-bit system, INT_MAX is typically 2^31-1, which would
require at least 2GiB of memory).
setupsquares ()
{
int i;
for(i = 0; i < INT_MAX; squares[i * i++] = true);
If i can go up to INT_MAX-1, then i*i can go up to (INT_MAX-1) squared,
which is outside the bounds of the array. But you almost certainly won't
be able to allocate an array that large (for INT_MAX == 2^31-1,
that's approximately 4 Exabytes).
It doesn't matter because i*i++ is undefined behavior twice!
i*i gives overflow and overflow of int is not defined
i*i++ itself is undefined behavior as the side effect on ++ is againxt
the rule that accessing the variable i more than once while ++ is in
that statement - so anything is broken.
--
Tschau/Bye
Herbert
Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2R Deutsch ist da!
.
- References:
- Segmentation Fault
- From: Rahul
- Re: Segmentation Fault
- From: Nobody
- Segmentation Fault
- Prev by Date: Re: Segmentation Fault
- Next by Date: Re: Segmentation Fault
- Previous by thread: Re: Segmentation Fault
- Next by thread: Re: Segmentation Fault
- Index(es):
Relevant Pages
|