Reason behind Segmentation Fault - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Reason behind Segmentation Fault

Share This

At the time of software development, one of the most common problems is errors like a Segmentation fault, also called SegFault. Here we will discuss, what a SegFault is?

Virtual memory in a computer can be created in 2 ways: pages or segments.

--- Paging means that the memory is divided into pages of equal size, containing words of memory in it.

--- Segmentation means that every process has a segment of the memory of the needed size, with gaps of empty memory blocks between the segments.

The operating system knows the upper limit of every segment, and every segment begins at a virtual address 0. When a program accesses a memory block, it calls a virtual address that the Memory Management Unit (MMU) maps to a real address.

If the operating system sees that the requested address doesn't match any valid address in the segment, it will send a signal to the process terminating it.

SegFaults are the direct result of a memory error.

The program has a bad pointer, a memory leak, or any kind of error that makes it access the wrong memory address.

To correct these errors you need to check pointers and arrays for errors.

Let us consider an example, where an input is being taken from the terminal.
#include <stdio.h> int main () { int n; printf("Enter a value : "); scanf("%d", n); printf("The result of %d^2 is %d", n, n * n); return 0; }
Did, you find any error? This program will not run. It will show you segmentation errors at run-time. Here I have done a mistake. I have not added & before n in scanf("%d", n). Hence, be very careful when you are writing a program.



Happy Exploring!

No comments:

Post a Comment