Segmentation Fault???

Segmentation Fault???

·

2 min read

Segmentation faults (segfaults) are memory related errors that causes programs to crash, when the program tries to read or write an invalid or illegal memory location. Segfaults happen in low level programming languages (C, C++, Fortran, etc) where memory management is in part done by the user(programmer).

Program memory is divided into segments; text segment for program instruction, data segment for variables defined at compile time, stack segment for function variables and heap segment for memory allocated during runtime. Note that the data segment is divided into two part a read-only part for constants and string literals and read and write part.

A program would segfault when a variable is referenced outside where it is stored in memory or trying to write to the read-only segment of a program memory. Typically segfaults occurs when accessing an invalid element in an array, misuse of pointers variables or trying to accessing a NULL address.

Examples of Programs That Would SegFault

All programs are written in C

1. Accessing Out of Bound Memory in Arrays

//This program accesses memory out of bound in an array

int main(){
      int numbs[3]; //Initialising the array

      numbs[8] = 9;//Writing to an out of bound memory

      return (0);
}

2. Modifying a String Literal

//This program tries to modify a string literal

int main(){
      char *str = "String Literal"; //Initialising string

      *str = 'T'; //Trying to modify first letter of the string

      return (0);
}

3. Reading/Dereferencing an Uninitialised Pointer

//This program dereferences an uninitialised pointer

#include <stdio.h>

int main(){
      int *ptr; //Declaring pointer ptr

      printf("%d", *p); //reading an uninitialised pointer

      return (0);
}

4. Accessing Freed Memory

//This program tries to access freed memory

#include <stdio.h>

int main(){
      int *ptr; //Declaring pointer ptr

      ptr = malloc(sizeof(int)); //Allocating memory to ptr

      *ptr = 576; // Writing to ptr

      free(ptr); //deallocating memory from ptr

      *ptr = 8097; //writing to a freed memory

       return (0);
}

5. Writing to a NULL pointer

//This program tries writes to a NULL pointer

int main(){
      float *ptr = NULL; //Initialising pointer ptr

      *ptr = 327; //Writing to ptr

      return (0);
}

6. Stack Overflow

//This program has a recursive function without a base case

#include <stdio.h>

int sumofn(int);

int main(){
      int number = 9; //Initialising number

      printf("The sum is %d", sumofn(9)); // calling and printing sumofn() function
      return (0);
}

//Recursive Function: Supposed to return sum of n numbers
//but does not have as base case

int sumofn(int num){

      return (num + sumofn(--num));

}

Thank you for reading...

Written By: Eseh Tony

Social Media Handles: LinkedIn, GitHub