- You are trying to write to a buffer which you have never allocated space
for. In the following example, we write to p[5], but there has
never been any memory space allocated to the pointer p.
char *p;
p[5] = 'a';
- You are trying to use a pointer which you have not pointed at allocated
space. For example, we want to use t to access parts of the
array p, but we forget to point t into the array:
char *t;
char p[10];
t[5] = 'a';
- You are trying to use a pointer which you have not allocated space for.
char *t, a;
a = t->field;
- You are trying to use an array index which is out of range for the size
of the array.
float t[10], a;
a = t[12];
- You are trying to dereference a NULL pointer.
int *p, a;
p = NULL;
...
a = p->field;
- You are trying to dereference through a NULL (or undefined) pointer.
Here are some examples:
typedef struct mystruct
{
int field;
struct mystruct *next;
}
struct mystruct *a;
int b;
a = NULL;
b = a->field;
Here, a is NULL, so a->field is illegal. In the next example, we've
allocated a struct for a, so a->next is legal, but is garbage until we
allocate something to it, so a->next->field is illegal.
struct mystruct *a;
int b;
a = malloc (sizeof struct mystruct);
b = a->next->field;
- You have read a function prototype, thinking it allocates and fills a
struct (see the man page for
times
), when really it tries to
fill a struct that it assumes YOU have allocated.
#include
struct tms *buf;
times ( buf );
Here, we have passed an uninitialized pointer to times()
,
when what it expects is the address of an allocated struct of type
tms
. When times
tries to fill this, it causes
the segfault.
- You have written too much data into an array.
char buf[10];
strcpy ( buf, "123456789012345" );
- You have assumed that the operating system will zero out memory when it
allocates it.
int a[2];
a[0] = 'A';
printf ( "%s\n", a );
If the array a has been zeroed upon allocation, then this will
print the string "A" to stdout and continue normally. This is because a[1]
will be seen by printf()
as a null-terminator. If the array
is not pre-zeroed, then the printf()
will print the character
'A', followed by whatever follows it in memory until either it hits a
random null character, or causes a segmentation fault. The above could be
rewritten to avoid this runtime error as:
int a[2];
a[0] = 'A';
a[1] = '\0';
printf ( "%s\n", a );
The C language does not require the operating system to zero memory upon
allocation, so you should assume that it hasn't been when writing code that
should be portable. This particular error is perpetuated by teaching
students using compilers or O/S's which do zero the memory for you. These
systems hide this error until you try to port the code to another system.
For this type of error, you want to key your search toward buffers that you
should have allocated, array range and size checks, and functions which pass
structs and struct pointers.