When do segmentation faults happen in C?
- User
When do segmentation faults happen in C?
Assistant
Segmentation faults (segfaults) in C happen when your program tries to access memory it doesn't have permission to access, or that doesn't exist. This is usually due to undefined behavior, and the operating system steps in to kill the process.
Here are the most common causes:
1. Dereferencing a NULL or invalid pointer
int *p = NULL; *p = 42; // Segfault
2. Accessing memory after it's been freed
int *p = malloc(sizeof(int)); free(p); *p = 42; // Segfault (use-after-free)
3. Accessing memory out of bounds
int arr[5]; arr[10] = 42; // Segfault (or undefined behavior)
4. Stack overflow
void recurse() { int big[10000]; recurse(); // Eventually segfaults due to stack exhaustion }
5. Writing to read-only memory
char *s = "hello"; s[0] = 'H'; // Segfault (string literals are read-only)
6. Using uninitialized pointers
int *p; *p = 42; // Segfault (p points to garbage)
7. Incorrect pointer arithmetic
int *p = malloc(5 * sizeof(int)); p += 100; *p = 42; // Segfault (out of bounds)
Summary
A segmentation fault is the OS saying:
"You're touching memory you shouldn't."
To avoid them:
- Always initialize pointers.
- Check for
NULLaftermalloc. - Stay within array bounds.
- Don’t use memory after freeing it.
- Use tools like
valgrindorAddressSanitizerto catch issues early.
Let me know if you want help debugging a specific segfault.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.