The dreaded SIGSEGV !

Segmentation Fault or SIGSEGV is a dreaded error of most C programmers. It mostly occurs due to invalid access of memory. Most of the times the invalid memory access is a mistake. However recently one of my friend asked me a question (who was asked the same in an interview) as to what happened if an arbitrary address is accessed?

The question was as follows:

#include <stdio.h>
int main(int argc, char *argv[])
{
    int *p;
    p = (int*)1;
    printf("%d  %d", p, *p);
    return 0;
}

Now I had never come across a scenario where you assign a value directly to a pointer variable and my first thought was, would this even compile? As a matter of fact it did, when I did compile with gcc. But on running the output file, I got the dreaded Segmentation Fault.

Now curious as to why, I stepped through the code using gdb and this is what I stumbled upon:

breakpoint 1, main () at test.c:6
6 p = (int*)1;
(gdb) p p
$1 = (int *) 0x0
(gdb) n
7 printf("%d %d", p, *p);
(gdb) p p
$2 = (int *) 0x1
(gdb) p *p
Cannot access memory at address 0x1
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x00000000004004ac in main () at test.c:7
7 printf("%d %d", p, *p);

Now let’s dissect what exactly is going on. Variable is a pointer variable, means it can hold an address. Since its an integer pointer, p can hold address of an integer variable. Now when we assign (int*)1 to p, what is happening is 1 is being assigned to p. But 1 is not being assigned directly, since 1 is prefixed with (int*) which is essentially casting 1 as an address of an integer variable. Hence p is being assigned an address 0x01 which is a valid instruction! Now in all probability, 0x01 is a valid address, but most definitely not a valid address for the program we are running. (We know the OS and other programs are already running, so we can be certain some other process is running at the first memory location, which is a valid address, but not valid for our program to access!) Hence on trying to print the value at this address, we encounter Segmentation Fault!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s