UMBC CS 201, Fall 06
 UMBC CMSC 201 Fall '06 CSEE | 201 | 201 F'06 | lectures | news | help Search Notes:

# Segmentation Faults

A segmentation fault occurs when a program tries to access a memory location forbidden by the operating system.

## Common Causes

• Trying to access an array element that is beyond the length of the array. int array[10]; for(i = 1; i <= 10; i++) { array[i] = i; } This code is trying to write to the 11th element of the array, but space was allocated for only 10 elements. As buggy as this code is, it may or may not cause a segmentation fault. If the address of the non-existent 11th element is not within your memory space, there will be a segmentation fault. If that address is within your memory space, this code will either write over one of your other variables, or will run fine if that address isn't being used. No matter what the result, the code is buggy and needs to be fixed.

• Being careless about the edges of a 2-dimensional array
Checking neighboring elements in a 2 dimensional array must be done carefully so that you are not accessing memory that is beyond the edges of the array (the same problem, just enlarged). for(i = 0, i < ROWS; i++) { for(j = 0; j < COLS; j++) { if(board[i][j] == 'X' && board[i][j-1] == 'X' && board[i][j+1] == 'X') { vertical++; } Oops, we looked off of the edge !
Buggy ?    Definitely
Seg Fault ?     maybe, maybe not

• Uninitialized Pointers int x, *xPtr; *xPtr = 5;
• Dereferencing a NULL pointer

Buggy Code :

while(target != curr -> data && curr != NULL) { prev = curr; curr = curr -> next; } Although we want to traverse the list until we find the target or reach the end of the list, if the target value is not in the list, curr will be NULL when the end of the list is reached. At that time, when we try to look at data in the node that curr's pointing to, we'll get a seg fault because curr is NULL.

Corrected Code :

while(curr != NULL && target != curr -> data) { prev = curr; curr = curr -> next; } This does NOT cause a segmentation fault, because C uses lazy evaluation. If curr is NULL, the code following the && is never executed.

• Trying to free() memory that you didn't dynamically allocate int x, *xPtr; xPtr = &x; free(xPtr);

CSEE | 201 | 201 F'06 | lectures | news | help

Tuesday, 22-Aug-2006 07:14:08 EDT