Segmentation Fault while Loading 8-bit windows bitmaps (no answer but a new question)

what is a segmentation fault? why does it happen? when? what can i do that it not happens?

what is a segmentation fault?

The Jargon File has a reasonable explanation:

[Unix] 1. [techspeak] An error in which a running program attempts to access
memory not allocated to it and core dumps with a segmentation violation
error. This is often caused by improper usage of pointers in the source
code, dereferencing a null pointer, or (in C) inadvertently using a
non-pointer variable as a pointer. The classic example is:

int i;
scanf ("%d", i); /* should have used &i */

why does it happen? when?

As above; it happens when a program tries to access memory that it hasn’t
been allocated. The operating system kills the program off with this error
message so that it doesn’t take the whole system down.

what can i do that it not happens?

Don’t try to access memory you haven’t been allocated :>

Specifically, the most common causes are trying to use a NULL pointer, and
running off the end of an array.

In the first case, something like:

SDL_Surface *surface;

surface = IMG_Load (“somefile.png”);
printf (“Surface is %dx%dx%dbpp.\n”,
surface->w, surface->h,
surface->format->BitsPerPixel);

If the file “somefile.png” doesn’t exist or is unloadable for any other
reason, IMG_Load() will return a NULL pointer. In this case, the above
program will segfault when it tries to access that pointer.

To avoid this, ALWAYS check the return value of functions that allocate
memory. The above should be:

surface = IMG_Load (“somefile.png”);
if (surface == NULL)
{
fprintf (stderr, “Failed to load somefile.png: %s.\n”,
IMG_GetError());
return FALSE;
}
printf ("…");

In the case of arrays:

int numbers [MAX_NUMBERS];
int i;

/* initialise the numbers[] array to zero */
for (i=0; i<=MAX_NUMBERS; i++)
numbers[i] = 0;

The above code overflows the array by one; it should be i<MAX_NUMBERS. The
above code should segfault; whether it will or not is anyone’s guess.
Different platforms are more tolerant of sloppy code like this; I had a
program on linux that worked fine, but when cross-compiled to Win32 it
crashed. After spending quite a while hunting down the problem, I found a
really dumb error like the above, only much worse. For some reason linux let
the program keep running, but Windows stopped it. (I always figured it would
be the other way around, since random user programs seem to have an easier
time crashing Windows than linux.)On Tue, 25 Dec 2001, Dan wrote:


Mike.
(too bored to write a short, simple answer)