কম্পিউটার টিউটোরিয়াল

C/C++-এ সেগমেন্টেশন এরর (Segmentation Error) খোঁজা (GDB ব্যবহার করে)


সেগমেন্টেশন এরর হলো একটি রানটাইম এরর (runtime error), যা মেমরি অ্যাক্সেস ভায়লেশন (memory access violation) এর কারণে হয়, যেমন ভুল অ্যারে ইন্ডেক্স অ্যাক্সেস করা, রস্ট্রিক্টেড এড্রেস পয়েন্ট করা ইত্যাদি। এই আর্টিকেলে আমরা GDB টুল ব্যবহার করে এই টাইপের এরর কীভাবে ডিটেক্ট করতে হয় তা দেখব।

কোড এবং এরর লোকেট করার ধাপগুলো নিচে দেওয়া হলো।

উদাহরণ কোড

#include <stdio.h>

int main() {
    int* ptr = NULL;
    *ptr = 1; // অজানা মেমরি লোকেশন অ্যাক্সেস করার চেষ্টা
    printf("%p\n", ptr);
}

কোড কম্পাইল করুন `gcc -g program_name.c` দিয়ে, এবং রান করুন `./a.out` দিয়ে।

আউটপুট

soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out
Segmentation fault (core dumped)

সেগমেন্টেশন এরর ঘটেছে।

লিখুন `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 
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: .
Find the GDB manual and other documentation resources online at: .
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)

`r` টাইপ করে এন্টার দিন।

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)

এভাবেই আমরা সফলভাবে এররটি খুঁজে পেয়েছি, এখন GDB থেকে কুইট করুন।

(gdb) quit
A debugging session is active.
Inferior 1 [process 2794] will be killed.
Quit anyway? (y or n) y
  1. C++-এ ট্রেন স্টপেজ স্টেশন সংখ্যা বের করুন

  2. OpenCV-এ C++ ব্যবহার করে উপবৃত্ত আঁকা

  3. OpenCV-এ C++ ব্যবহার করে রেখা আঁকা

  4. সি++ প্রোগ্রাম দিয়ে অন্য প্রোগ্রাম লঞ্চ করা