Re: Segmentation Fault



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!
.



Relevant Pages

  • Re: [PATCH v3 2/2] bsearch: prevent overflow when computing middle comparison element
    ... overflow situation when computing the middle element for comparison. ... maximum int value. ... approaches the maximum unsigned int ... at the highest extreme of the array. ...
    (Linux-Kernel)
  • Re: Pointer arithmetics in 2D arrays
    ... so it becomes int *. ... are, strictly speaking, breaking the rules. ... overstepping the bounds of an array. ... overflow was declared UB in the first place (i.e. speeding up run time by ...
    (comp.lang.c)
  • Re: bad programming practice?
    ... int array; ... to define an array after the retreival (via input data ... since calloc() doe size checking for you, ... The thing is that you might overflow your type's here, ...
    (comp.lang.c)
  • Re: First program in C - what is going on with function returns?
    ... "int main "? ... There is no need to return an array. ... Return a pointer to the string ... Visit http://www.ecomstation.de the home of german eComStation ...
    (comp.lang.c)
  • Re: type of array index?
    ... >> must be able to represent any possible array subscript. ... dozen other coders) overflows that int but size_t would have worked. ... whether the index will overflow ten years later and crash some ...
    (comp.lang.c)