What is segmentation fault in C++ and how to fix it?
Hi everyone! I just started learning C++ and I keep encountering a "Segmentation fault" (or "Segfault") error. The program just crashes, and I don't understand why. Here's an example of my code:\n\n```cpp\n#include \nusing namespace std;\n\nint main() {\n int* ptr;\n *ptr = 10; // Segmentation fault happens here\n cout << *ptr << endl;\n return 0;\n}\n```\n\nI declared a pointer `ptr`, but didn't assign an address to it. When I try to write the value 10 to this pointer, the program crashes. Why does this happen? I thought a pointer is just a variable that stores an address, and I can write a number into it.\n\nAnother example that doesn't work for me:\n\n```cpp\n#include \nusing namespace std;\n\nint main() {\n int arr[5] = {1, 2, 3, 4, 5};\n for (int i = 0; i
No answers yet.
Log in to leave an answer