
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Segmentation Error in C and C++ Using GDB
The segmentation error is one of the runtime error, that is caused because of the memory access violation, like accessing invalid array index, pointing some restricted address etc. In this article, we will see how to detect this type of error using the GDB tool.
Let us see the code and respective steps to locate the error.
Example
#include <stdio.h> main() { int* ptr = NULL; *ptr = 1; //trying to access unknown memory location printf("%p\n", ptr); }
Compile the code using ‘gcc –g program_name.c’, and run using ‘./a.out’
Output
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out Segmentation fault (core dumped)
The segmentation error occurred.
Write ‘gdb ./a.out core’
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ gdb ./a.out core GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git Copyright (C) 2018 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from ./a.out...done. /home/soumyadeep/Cpp_progs/core: No such file or directory. (gdb)
Type ‘r’ and press enter.
Starting program: /home/soumyadeep/Cpp_progs/a.out Program received signal SIGSEGV, Segmentation fault. 0x000055555555465e in main () at 1230.find_seg_error.c:5 5 *ptr = 1; //trying to access unknown memory location (gdb)
So we have got the error successfully, now quit the GDB
(gdb) quit A debugging session is active. Inferior 1 [process 2794] will be killed. Quit anyway? (y or n) y
Advertisements