Fix 'Segmentation Fault' in Online C Compiler
🧠 What is a Segmentation Fault in C?
A segmentation fault occurs when a program tries to access a memory area it shouldn't — for example, dereferencing an invalid pointer or accessing memory out of bounds.
🚨 Common Causes in Online C Compilers (and Fixes)
✅ 1. Uninitialized or NULL Pointer Dereference
int *ptr; *ptr = 10; // ❌ Segmentation Fault
Fix:
int *ptr = (int *)malloc(sizeof(int)); *ptr = 10; printf("%dn", *ptr); free(ptr);
✅ 2. Array Index Out of Bounds
int arr[5]; arr[10] = 100; // ❌ Invalid memory access
Fix:
int arr[5]; arr[4] = 100; // ✅ Within valid range
✅ 3. Improper Use of scanf()
int num; scanf("%d", num); // ❌ Segmentation fault
Fix:
int num; scanf("%d", &num); // ✅ Correct usage
✅ 4. Using Freed Memory
int *ptr = malloc(sizeof(int)); free(ptr); *ptr = 5; // ❌ Illegal memory access
Fix: Avoid using ptr after freeing it, or set it to NULL.
✅ 5. Stack Overflow (Deep Recursion)
void recurse() { recurse(); // ❌ No base case leads to stack overflow }
Fix:
void recurse(int count) { if (count <= 0) return; recurse(count - 1); }
🛠️ How to Debug in Online C Compiler
- Add printf() statements to check variable values.
- Isolate the faulty block and test separately.
- Use tools like Online C Compiler with input/output preview.
- Avoid dynamic memory usage unless necessary.
💡 Pro Tip
Always initialize pointers and arrays properly, and double-check loops and input handling when using online compilers — they are more sensitive to runtime crashes due to limited memory.
✅ Conclusion
Segmentation faults are common, especially in C. But with careful pointer handling, bounds checking, and input validation, you can easily avoid them — even on an online compiler.