In the journey of programming,we may come across many errors.Let us discuss one of the most frequently facing error Segmentation fault.
Segmentation means addressing space in memory.Therefore,segmentation fault means fault in addressing memory i.e., illegal accessing of memory. It occurs when the hardware detects an attempt to refer a non existent segment or a location that is out of bounds of segment.
segmentation fault may occur due to improper scanf statement.
Whenever we try to access the array index that is out of bounds,we encounter segmentation fault.
We get segmentation fault when we try accessing uninitialized pointers.
Segmentation fault may occur due to dangling pointeri.e., trying to access an object whose contents have already been deleted.
segmentation fault also occur because of Stack Overflow or Buffer Overflow.Especially while implementing recursionwith improper base condition.
What is Segmentation Fault?
Segmentation means addressing space in memory.Therefore,segmentation fault means fault in addressing memory i.e., illegal accessing of memory. It occurs when the hardware detects an attempt to refer a non existent segment or a location that is out of bounds of segment.
Let us see some of the scenarios.
Example 1:
segmentation fault may occur due to improper scanf statement.
main() { int a; scanf("%d",a); // error missing '&' }
Example 2:
Whenever we try to access the array index that is out of bounds,we encounter segmentation fault.
main() { int a[10]; printf("%d",a[10000]); //error }
Example 3:
We get segmentation fault when we try accessing uninitialized pointers.
main() { int *p; printf("%d",*p); //error }
Example 4:
Segmentation fault may occur due to dangling pointeri.e., trying to access an object whose contents have already been deleted.
main() { int *p,res=0; p=&res; free(p); printf("%d",*p); }
Example 5:
segmentation fault also occur because of Stack Overflow or Buffer Overflow.Especially while implementing recursionwith improper base condition.
main() { main(); }
Tips to Fix:
- As we have seen ,segmentation fault is mostly due to improper handling of pointers.So,we need to be cautious while dealing with pointers.
- Ensure '&' operataor is properly used or not.
- A pointer must be initialized before performing any operations.
No comments:
Post a Comment