I am trying to read the value at random memory location using the following c code
main()
{
int a,*b;
printf("enter the value of a");
scanf("%d",&a);
b=a;
printf("%d\n%d\n",a,*b);
getch();
}
But the program is crashing when some negative values or even when zero is entered in place of variable a through scanf.
What I am doing wrong? Does the pointers dont have negative values?
The thing is that as you are probably running on a modern, full service operating system and it provides a more complicated abstract machine than the one described in most intro to c programming books.
In particular, there are OS imposed restrictions on access to arbitrary addresses. You don’t notice this when you look at addresses associated with standard variables because you do have permission to use the stack and the data segment, and the
allocfamily of functions takes care of making sure that you have permission to access the parts of the heap that they hand you.So, what you are doing is accessing memory for which you do not have permission, which results in a failure called a “segmentation fault” on most OS, and that abruptly ends your program.
What can you do about it?
Allocate a big block on the heap, by calling
char *p = malloc(1000000);and then find the starting and ending addresses with something likeprintf("start:\t%p\nend\t%p\n",(void*)p,(void*)(p+1000000));and only entering numbers in that range.Note that the
%pspecifier print specifier outputs in hexadecimal, so you probably want to enter address in the same base. The standard library functionstrtolwill be helpful in that regard.A more sophisticated approach would be to use your OS’s API to request access permission for arbitrary address, but for some values the OS is likely to simply refuse.