Avatar ·

What is segmentation fault in C++ and why does it occur?

Hello everyone! I'm a beginner in C++ and encountered a confusing error. My program compiles without errors, but when I run it, it crashes with the message "Segmentation fault (core dumped)". I don't even understand what this means.\n\nHere's a simplified code that causes this problem for me:\n\n```cpp\n#include \nusing namespace std;\n\nint main() {\n int* ptr;\n *ptr = 42; // Crash happens here\n cout << *ptr << endl;\n return 0;\n}\n```\n\nI simply declare a pointer `ptr` and try to write a value to it. Why does the program crash? I've heard it's somehow related to memory, but I don't understand the details.\n\nI also have another example with an array:\n\n```cpp\nint arr[5] = {1, 2, 3, 4, 5};\nfor (int i = 0; i <= 5; i++) {\n cout << arr[i] << endl; // Error on the last iteration }