×

Segmentation Fault in C

Segmentation Fault in C

In the C programming language, segmentation fault or segmentation violation or core dump is a condition that the hardware component raises to protect the memory by indicating to the operating system that the software has attempted to access the area of memory restricted for security purposes. In other words, it is a runtime error caused due to accessing memory that does not belong to specific software. A segmentation fault occurs due to a memory access violation.

A segmentation fault occurs when a snippet of code does a read and write operation where only a read operation should be conducted. It might occur even when there is stack overflow as it will request extra memory, which the CPU does not consist of. It can be defined as an error illustrating memory corruption.

Errors that lead to a segmentation fault

  • Format control strings - in the C programming language, the specific string's reading and writing involves format specifiers or format control strings, for example, %d, %s, %f, and so on. These format control strings present in printf and scanf statements must be of equal number as initialized at the beginning of the program or are manipulated at later stages. The specifiers must match the data type of variable that will be printed or read.
  • Failure of initializing a pointer - while accessing a pointer in C, the variable must have a valid address, and only then can it be accessed. Ensuring that all the pointers are initialized to a valid memory area will not throw any segmentation fault in this case. Proper initialization must take place for the smooth execution of a program.
  • Acquiring memory beyond array limits - violating an array's bounds while using array indexing leads to a segmentation fault. If the array limit exceeds the specified index value, it will throw an error, and it is defined as Undefined Behaviour (UB) as per ISO C standard. Undefined behavior results from executing a program whose behavior is prescribed to be an unpredictable one in a language to which the code adheres.
  • Imprecise usage of "address of (&)" and "dereferencing (*)" operators - In C, once a pointer variable is declared, it must be initialized with a valid memory address. Ampersand (&) is also used to scan the user input; incorrect usage of "&" gives a possible bug. Dereferencing a variable is used to return the location of a variable.
  • Out of bound access - this event occurs when a value is accessed or changed at an index value greater than the array size. It will keep on accessing a memory space that specifically does not belong to the error hence throws an error.
  • Buffer overflow - buffer overflow or buffer overrun is a deviation in a program that occurs when writing data to a buffer. It overruns the buffer's boundaries and overwrites other memory locations. Buffers are spaces of memory set aside to hold data while moving different program sections or between the programs. 
  • Trying to access memory that the program does not have access to, like kernel structures, etc., throws a violation error.
  • This error occurs during accessing a freed memory location, which is a memory piece previously used by some object but is free now.

Examples

  • Writing to read-only memory.
 int main(void) {
            char *s = "Delhi is the capital of India";
            *s = 'A';
} 
  • Scanf usage
 #include <stdio.h>
{
            int p = 10;
            scanf("%d",p);
            return 0;
} 
  • Out of array
 #include<stdio.h>
{
            int arr[10];
            arr[11] = 100;
return 0;
} 
  • Stack overflow
 #include<stdio.h>
int main(void)
{
            main;
            return 0;
} 

How to handle segmentation fault

Always check all the program code that uses pointers, subscripts of an array, dereferencing operator (*), and address operator (&). Segmentation fault usually means the program has an error and needs debugging. Sometimes, it is also possible for someone to intentionally cause such failure for testing, debugging platforms where direct access to a specific memory is necessary. In latter cases, the system must allow the program to run, albeit of the fault occurrence. In cases like so, as the system allows, it will be possible to handle the event and drastically increment the processor program counter to jump over the instruction to continue the ongoing execution.

Many operating systems (OS) such as Linux and windows have a special ability to handle a segmentation fault or a core dump. It depends on the architecture of that particular system. The executing program handles the event and extracts information about the state such as processor registering values, stack trace, line of code snippet where it was triggered, and so on.


Related Topics

Command line arguments in C

Command line arguments in C The arguments that are generally passed from the line of command are referred to as command line arguments. These command line arguments are always handled by...

3 minutes read.

Factorial Program in C Using While Loop

Before looking into the mechanism of factorial program, first, you have to understand about the working of a while loop. While Loop The syntax that has been used for the “while” loop...

4 minutes read.

Queue implementation in C

In the C programming language, the queue is the abstract concept that is similar to stacks. However, it is the part of the data structures that work opposite to that...

4 minutes read.

Dos.h Header File in C Language

Dos.h is a header file in C. Interrupt handling, sound generation, date and time functions, and other tasks can be performed using the functions in this library. This is exclusive to...

4 minutes read.

C Math Library

C Math Library The <math.h> header defines various mathematical functions and one macro. Many functions are available in this library to take double as an argument and then return double as...

4 minutes read.

Nested loop in C

Definition of Nested Loop A nested loop is generally used when we want to run a loop statement inside another loop statement. This kind of loop is also known as a...

3 minutes read.

Find out Power without using POW function in C

Introduction: In this discussion, we will discuss how we find out power without using the POW function in C. In this article, you'll understand how to compute integer powers in...

3 minutes read.

Program to Find Mode of an Array in C

Mode is the highest occurring value or number in a given set of data elements. In a group of data values, a value that occurs most frequently is considered to...

3 minutes read.

Expressions in C

Expressions in C: In the C programming language, an expression defines a formula in which the operands are linked to each other by using operators to compute the value. The operand...

4 minutes read.

C –Structure

C structure is a collection of different types of data that is grouped together. It is used to represent records.Structkeyword is used to create a structure. Each element of a...

1 minute read.

Calendar application in C

Introduction to the calendar application We all are familiar with the calendar. It plays a crucial role in our daily life. We run toward the calendar whenever we want to know...

6 minutes read.

If else Programs in C Programming

If else Programs in C programming The if-else statement in C is based on some particular conditions to perform the operations. If and only if the given condition is valid, the operations listed in...

4 minutes read.

Distance Vector Routing Protocol Program in c

A distance-vector routing protocol is one of the foremost instructions of routing protocols in pc conversation principle for packet-switched networks. The hyperlink-nation protocol is the alternative foremost class.The Bellman-Ford set...

4 minutes read.

Types of Array in C

What is an Array? One value can be stored in a variable at once. How many variables will you need if you have 100 values? Well, the answer isn't 100. It...

14 minutes read.

Random Access - Lseek in C

Introduction lseek is a system call that is used to alter the location of the read/write pointer of a file descriptor. The lseek system call basically moves the current read/write location...

4 minutes read.

Limitations of Inline Function in C

The compiler is unable to conduct inlining in two instances. It just accepts the inline definitions and produces space for the function in the same way it does for a...

3 minutes read.

FIFO Example in the C Language

FIFO is an acronym that means "First In, First Out." It is a data structure handling method in which the first element is handled first, and the last element is...

3 minutes read.

Derived Data Types in C

A variable in a program occupies some space in the computer's memory where some value is stored. Each variable in C has an associated data type. A value to be...

4 minutes read.

Flow Chart of Do while loop in C

This is a flowchart that represents the process of executing the Do while loop in the C programming language Generally, as we know there are three main components of Do While...

3 minutes read.

Hook() function in C

Use of hook () function in C Introduction:  The hook () is a function used in the C programming language. The basic concept of the hook() function is that it can remove the function...

3 minutes read.