Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: May 28, 2024
Difficulty: Easy

Segmentation Fault in C/C++

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

A segmentation fault in C occurs when any program tries to access a part of memory that it is not allowed to access. In simple words,  In C programming segmentation fault (Also known as segfault) occurs when any program tries to read or write to a memory location that has not been allocated for the program.

In this article, we will learn about the segmentation fault in C and C++ in detail. We will also look at the reasons that cause a segmentation fault in C++ and C with their prevention and handling.

segmentation fault in c

 

What is Segmentation Fault in C and C++ Programming?

A Segmentation Fault in C programming occurs when a program tries to access or modify a memory location that hasn't been allocated to it. Memory management in C is manual, and mistakes in managing memory can result in Segmentation Faults.

When a segmentation fault occurs, the program is terminated, and an error message is usually displayed, indicating the offending code line. Debugging tools like GDB can be used to identify and fix the issue. Segmentation faults can be challenging to diagnose and fix, as they often indicate memory-related errors. Proper memory management practices, including initializing pointers, bounds checking, and avoiding buffer overflows, can help prevent such errors.

Common Causes of Segmentation Fault in C/C++

A segmentation fault in C occurs when a program attempts to access a memory location that it's not allowed to access. It is a common runtime error in C and C++ programming. It occurs when a program attempts to access a memory location that it's not allowed to access, typically due to memory protection mechanisms enforced by the operating system.

Following are some of the common causes of segmentation faults in C++ and C :

  • When a program tries to access an out-of-bound memory location.
  • When a code tries to access invalid memory.
  • When a program tries to write to a read-only memory location.

Following are some C programming errors that cause these faults :

  • Dereferencing or allocating any pointer to an uninitialized pointer. These are called wild pointers, which point to any random memory location.
  • Dereferencing or allocating any pointer to a freed pointer. These are called dangling pointers, which point to a memory location that has been freed using free command.
  • Null pointers point to a memory location that is not part of the process's address space.
  • Stack Overflow - This happens when a program tries to use more memory than the memory allocated to the call stack.
  • Buffer overflow - It often occurs when the data in the local buffer exceeds its storage capacity.

You can also do a free certification of Basics of C++.

Let’s understand the above points with the help of the code below: 

  • C++

C++

#include <bits/stdc++.h>
using namespace std;
int main(){
   int *ptr_a = NULL; // ptr_a is assigned null value
   int *ptr_b;  // ptr_b is uninitialised pointer (wild pointer)
   int *ptr_c = (int *)malloc(10*sizeof(char));
                       // Memory allocated to ptrc
   free(ptr_c); // ptr_c is freed (dangling pointer)
   return 0;
}
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Common Segmentation Fault in C/C++ Scenarios

Null Pointer Dereference

A NULL pointer in C / C++ points to memory that does not exist. This may be the address 0x00000000 or any other defined value (as long as it is not a real address). Dereferencing a NULL pointer means trying to access whatever is pointed to by the pointer. The * operator is the dereferencing operator. Dereferencing a NULL pointer will result in undefined behaviour.

For a part of code like this 

int *ptr = NULL;
printf("%d", *ptr);


Dereferencing a NULL pointer will result in undefined behaviour.

Buffer Overflow

The buffer overflow occurs when we access any memory outside of the local buffer, e.g. -

  • C++

C++

#include <bits/stdc++.h>
using namespace std;
int main(){
   int arr[] = {1, 2, 3, 4, 5};
   int x = arr[10];
   cout<<x;
}

Output: Error: The output will be some garbage value or termination of program.

Here we are accessing the 10th index of the array arr, which is beyond its upper limit so any garbage value will be returned by the compiler.

Stack Overflow

The stack overflow occurs when we use more memory than the memory allocated to the stack, for example:

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

void fun(int x){
   fun(x);
   cout<<x<<" ";
}

int main(){
   fun(3);
}

Output: Error: stack overflow

Here the function fun calls itself infinitely, causing the recursive stack to exceed its memory.

Writing to Read-Only-Memory

Writing to read-only memory will result in a segmentation fault in C++ and C language.

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

int main(){
   char *s = "Coding Ninjas";
   *s = 'L';
   cout<<*s;
}

The above code will result in compile error with the following error:

error: invalid conversion from a string constant to ' char* '

Because we are trying to edit a constant data type.

Improper use of scanf or cin

In C and C++ scanf and cin expect the address of a variable as an input. In the program mentioned below, n is assigned the value 10 and assumes the address of n is 1000.

If we pass n to scanf(), the input from STDIN is stored in invalid memory 10, which should be 1000. It's a memory corruption that results in a segmentation fault. 

  • C++

C++

#include <iostream>
using namespace std;

int main(){
   int x = 10;
   cin>>" ">>x;
   return 0;
}

Output: Error: Program will terminate abruptly.

How to Fix Segmentation Faults?

Since segmentation fault in C++ and C occurs primarily due to invalid memory or out-of-bounds, it is necessary to check that any variable or pointer in the program always points to the correct memory location.

1. Writing to Read-Only Memory

As discussed above, we can't write to a const memory location. In such cases, we can use an array or string. For example,

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

int main(){
   char s[] = "Coding Ninjas";
   s[0] = 'L';
   cout<<s;
}

Output :

Loding Ninjas


Here we are making an array of characters that can be edited so changing the first index changed the output without any error.

Following are some measures to prevent the segmentation fault in C++ and C:

  • All pointers in the program must point to a valid memory location during the runtime.
  • Always initialize the pointer correctly.
  • In the case of multithreading, we can use semaphores to ensure that it should not use any memory to write by two or more concurrent threads.
  • After using a pointer, we must use the free() function to release that memory.

2. GDB Compiler

The GDB Compiler is a C (and C++) debugger. It enables your program to run up to a specified point, then pauses and reports the values of the specified variables at that moment, or it can step through the program line by line at a time, printing the values of every variable after each line is executed. The GDB debugger will help you to figure out which lines are responsible for the segmentation fault.

GDB Compiler

For the given code saved as main.cpp, we will first set the breakpoint on one or more lines using the command (gdb) b line_no.

Using the command (gdb) run we will start our debugging this will execute the program line by line and whenever we will encounter any line with a breakpoint the output of the variables

Will be printed in a.out and if there is some segmentation fault it will detect it and will display the line number in the terminal.

Preventing segmentation fault in C

How to Debug a Segmentation Fault in C?

We can debug a segmentation fault in C using the GDB compiler that tells us at which line the main error occurs.

Load your program into the GDB compiler. Make sure that you compile while debugging is enabled. If your program has a segmentation fault, the compiler will halt the compilation at the line where the segmentation fault occurs. Then, after you have spotted the line where the segmentation fault has occurred, inspect those variables or pointers that are causing the segmentations. 

Some common mistakes make a segmentation fault occur. Some of them are:-

  • Wrong index of an array
    In many cases, a segmentation fault occurs when you are trying to access the memory space which has not been allocated to the array.
  • Stack Overflow
    It happens when the memory runs out of the stack. It happens due to lots of local variables, an unrealistic amount of size of an array, a very large count of recursive calls, etc.
  • Modify a string literal
    As we have seen in the example above, it happens when we try to modify the string literals which are under the section of read-only memory.
  • Trying to access an already freed address
    This generally happens when we try to access a memory block with the help of a pointer that has already been freed.
  • Trying to dereference an uninitialized pointer
    An uninitialized or a NULL pointer does not point to a memory space. So, if you try to dereference it, a segmentation fault will occur.

Examples of Segmentation Fault in C/C++

Let us look at two examples of segmentation fault in C/C++:

Example 1: Array Out of Bounds

  • C++

C++

#include<iostream>

using namespace std;

int main() {
int arr[5];
arr[6]=42;
// Accessing an array element out of bounds
cout<< arr[6];
}

Output:

Segmentation Fault

 

Explanation:  In this example, an array arr of size 5 is declared, but then we attempt to access the element at index 6, which is out of bounds. This leads to a segmentation fault because we are accessing memory that doesn't belong to the array.

Example 2: Modifying a String Literal

  • C++

C++

#include <iostream>
using namespace std;

int main()
{
char* name;
name = "Ninja";

// Trying to modify read only memory
*(name + 1) = 'n';
return 0;
}

Output:

Segmentation Fault

 

Explanation: String literals are stored in a read-only memory section. This is why the following program might crash and result in a segmentation fault error, as the line *(name+1) = 'n' attempts to modify read-only memory.

Advanced Tips for Diagnosing and Fixing Segmentation Faults in C

Diagnosing and fixing segmentation faults in C can be challenging due to their nature of occurring at runtime. Here are some advanced tips to help tackle these errors:

  1. Use Debugging Tools:
  • Employ tools like gdb (GNU Debugger) to step through your code and examine the state of your program at various points.
  • Use valgrind to detect memory leaks and memory management issues that could lead to segmentation faults.

2. Memory Check Instruments:

  • Apply instruments like AddressSanitizer (available with compilers like GCC and Clang) to detect out-of-bounds accesses and use-after-free errors.

3. Code Review and Analysis:

  • Perform thorough code reviews focusing on pointer usage, array indexing, and memory allocation/deallocation.
  • Static analysis tools can help identify potentially risky segments of code that might cause segmentation faults.

4. Boundary Conditions Testing:

  • Pay special attention to boundary conditions in loops and during array access to prevent out-of-bounds errors.

5. Initialization Checks:

  • Ensure all pointers are initialized before use. Uninitialized or dangling pointers are common causes of segmentation faults.

6. Dynamic Memory Management:

  • Double-check dynamic memory allocations and deallocations to avoid memory leaks and dangling pointers.
  • Use tools or functions that automatically initialize memory, like calloc instead of malloc.

7. Signal Handlers:

  • Implement signal handlers for SIGSEGV to catch segmentation faults and log stack traces or other useful debug information.

8. Consistency in Pointers and Arrays:

  • Ensure consistency in the use of pointers and arrays, particularly with pointer arithmetic and array indexing.

9. Unit Testing and Assertions:

  • Employ unit tests to isolate and test individual functions or modules, which can help pinpoint the source of segmentation faults.
  • Use assertions within your code to verify assumptions about your program's state.

10. Careful Use of Recursion:

  • Be cautious with recursive functions, as deep recursion can lead to stack overflow, a common cause of segmentation faults.

11. Thread Safety:

  • In multi-threaded applications, ensure shared resources are properly synchronized to prevent concurrent access issues.

Frequently Asked Questions

What causes segmentation fault in C?

Segmentation fault in C happens when the program tries to access some memory but does not correctly define the pointer to do this before using it. It can also occur when it sometimes uses a variable's value as its address.

What is the segmentation fault in C in arrays?

A segmentation fault in C occurs in arrays when the program tries to access some memory space that is not allocated to the array. It generally happens due to wrong index values like -1 or more than the array size.

How to solve segmentation fault in C in Linux?

Removing the available lock files, removing and upgrading the repository cache, updating the distribution and package, and finally searching and removing the broken packages are the steps to handle segmentation faults in Ubuntu. CLI and GUI are two ways to resolve it.

What is segmentation fault 11 in C?

If segmentation fault 11 occurs, the program has tried to access a memory space it is not allowed access to. It can also happen if the program accesses a memory space, and how it tries to access it is not permitted.

Conclusion

In this article, we have discussed the segmentation fault in C++ and the Segmentation fault in C. We have explored various reasons for the segmentation fault in C++ and C programming languages with their prevention and handling.

Recommended Readings:

Happy Learning!

Topics covered
1.
What is Segmentation Fault in C and C++ Programming?
2.
Common Causes of Segmentation Fault in C/C++
2.1.
Following are some of the common causes of segmentation faults in C++ and C :
2.2.
Following are some C programming errors that cause these faults :
2.3.
C++
3.
Common Segmentation Fault in C/C++ Scenarios
3.1.
Null Pointer Dereference
3.2.
Buffer Overflow
3.3.
C++
3.4.
Stack Overflow
3.5.
C++
3.6.
Writing to Read-Only-Memory
3.7.
C++
3.8.
Improper use of scanf or cin
3.9.
C++
4.
How to Fix Segmentation Faults?
4.1.
1. Writing to Read-Only Memory
4.2.
C++
4.3.
2. GDB Compiler
5.
How to Debug a Segmentation Fault in C?
6.
Examples of Segmentation Fault in C/C++
6.1.
Example 1: Array Out of Bounds
6.2.
C++
6.3.
Example 2: Modifying a String Literal
6.4.
C++
7.
Advanced Tips for Diagnosing and Fixing Segmentation Faults in C
8.
Frequently Asked Questions
8.1.
What causes segmentation fault in C?
8.2.
What is the segmentation fault in C in arrays?
8.3.
How to solve segmentation fault in C in Linux?
8.4.
What is segmentation fault 11 in C?
9.
Conclusion