17
2012
Understanding Segmentation Fault with C Code Snippets
Coding is a difficult job for the best of us. It takes a lot of time, effort and patience. The fact that there are so many types of errors possible and most of them are misunderstood makes the job of coding very tedious. One of these irritating errors is the Segmentation Fault and in this stone I will try and explain why this error occurs and then how to solve them.
Segmentation is a memory management scheme that supports the user view of Memory. The essential requirement of memory management is to provide ways to dynamically allocate portions of memory to programs at their request, and freeing it for reuse when no longer needed. The user program deals with logical addresses; it never sees the real physical addresses. A program is a collection of segments. A segment is a logical unit as: main program, procedure , function , method , object, local variables, global variables , arrays and so on. The physical memory in a computer is managed by the operating system. It has different segments for different purposes, for example the segment used for storing data would be different to that used to store variables or texts. When we try to access the memory location outside of any allocated space segmentation fault occurs.
According to Wikipedia:
A segmentation fault (often shortened to segfault), bus error or access violation is generally an attempt to access memory that the CPU cannot physically address. It occurs when the hardware notifies an operating system about a memory access violation. The OS kernel then sends a signal to the process which caused the exception. By default, the process receiving the signal dumps core and terminates.
There are numerous reasons that cause segmentation fault in C. We represent them here with small C code snippets and then conclude the reasons for the same.
1.
void main()
{
char *p = "Fortystones";
p[ 3 ] = 'Y';
printf("%s",p);
}
Correct Code :
void main()
{
char p[] = "Fortystones";
p[ 3 ] = 'Y';
printf("%s",p);
}
Output:
ForYystones
Reason for the error: A string literal is normally stored in the read-only memory when the program is run to prevent actually changing the string constant. Hence in the first case because we are trying to write to the read-only portion of the memory we get a segmentation fault. However in the second case the string “Fortystones” is copied from the
read-only home to the p[] array. Thus modification is now permissible.
2.
void main()
{
char *p = NULL;
*p = 'F';
printf("%c",*p );
}
Correct code :
void main()
{
char *p = NULL;
char f = 'F';
p = &f;
printf("%c", *p );
}
Output : F
Reason for the error: If you dereference a pointer that stores the location 0×0 ( NULL ) then you’ll definitely get a segmentation fault, just as we did.
3.
int fact ( int num )
{
return num * fact( num - 1 );
}
void main()
{
int n;
printf("Enter the number\n");
scanf( "%d" , &n );
int ans = fact( n );
printf("The factorial is %d " , ans );
}
Correct code :
int fact ( int num )
{
if ( num == 1 ) {
return 1;
}
else {
return num * fact( num - 1 );
}
}
void main()
{
int n;
printf("Enter the number\n");
scanf( "%d" , &n );
int ans = fact( n );
printf("The factorial is %d " , ans );
}
Output: Here input provided is 5
Enter the number
5
The factorial is 120
Reason for the error: Recursion without base case leads to stack overflow which is another reason for causing segmentation fault.
4.
void main()
{
int i;
char arr1[ 15 ] = "Fortystones";
char arr2[ 20 ];
for ( i = 0; i < 20; i++ ) {
arr2[ i ] = 'a';
}
strcpy( arr1 , arr2 );
printf("%s",arr1);
}
Correct Code :
void main()
{
int i;
char arr1[ 21 ] = "Fortystones";
char arr2[ 20 ];
for ( i = 0; i < 20; i++ ) {
arr2[ i ] = 'a';
}
strcpy( arr1 , arr2 );
printf("%s",arr1);
}
Output :
aaaaaaaaaaaaaaaaaaaa
Reason for the error: The size of arr1 in the first case is insufficient to copy the contents of arr2. Hence we get the error in the first case due to buffer overflow whereas in the second case the size of the arr1 has been increased enough to accomodate arr2.
5.
void main()
{
char *a = "Forty";
free( a );
a = "Stone";
printf("%s",a);
}
Correct Code :
void main()
{
char *a = "Forty";
a = "Stones";
printf("%s", a );
}
Output:
Stones
Reason for error: Dereferencing a pointer that has been freed in the first case.
Conclusion: Now we can easily conclude that segmentation fault can occur due to one of the following reasons:
1. Trying to write to or modify the read – only portion of the memory.
2. Dereferencing a NULL pointer.
3. Recursion applied without a base case causing Stack Overflow.
4. Buffer Overflow.
5. Dereferencing a pointer that has been freed.
Related Posts
2 Comments + Add Comment
Leave a comment
Fortystones Lab Projects
Categories
- Articles (40)
- Idea (1)
- Review (5)
- Social Media (27)
- Trending Topics (13)
- Collection (28)
- How To (26)
- Linux (25)
- News (15)
- PHP (6)
- Project (1)
- Tutorials (34)
- Java (3)
- Programming (9)
- Wordpress (7)
Popular Posts
- 40 Basic Linux Command-line Tips and Tricks
- Tips and Tricks for Facebook Chat (Save History/ Video Chat/ Send Files)
- The First on the World Wide Web
- 40 Linux Shell Commands for Beginners
- Online Coding Zones for Programmers
- 13 years of Google: 1997- Present
- Special: Facebook Smiley, Special Text Symbols and ASCII Arts

An article by Raju Khanal






There is a mistake in the correct code for the 4th problem.
It should be “printf(“%s”,arr1);” in place of ” printf(“%s”,a); “
thanx…fixed it