975 views
0 votes
0 votes

int * p(void) 

int *x; 
*x=10; 
return (x); 


We create *x, and dereference it before assigning anything to it (x). Most likely, when we are declaring something on the stack, it will have a random value. The assignment - *x = 10 will try to write the value 10 to whichever address the pointer is pointing to (i.e. the value of x itself) 
, so then what's the issue i.e. when we can assign a value 10 at some random location pointed by x so then why does this result in segmentation fault ?

1 Answer

4 votes
4 votes

Good one. You told everything perfectly and the only question remaining is "why can't we write to some random location in memory?". Well, that is due to OS protection. Suppose we write to a random location and changes the memory content of some other process, that can crash rt? So, OS allows a process to modify only the memory allowed by it- in Segmented memory managed systems, a process can only access the memory in its assigned segments and when it accesses a memory outside that it gets segmentation fault. 

In a uniprocess system this protection is not needed. One of the main uses of virtual memory in addition to extension of memory address space is this memory protection. 

Related questions

2 votes
2 votes
3 answers
1
Laahithyaa VS asked Sep 9, 2023
937 views
. What will be the value returned by the following function, when it is called with 11?recur (int num){if ((num / 2)! = 0 ) return (recur (num/2) *10+num%2);else return 1...
0 votes
0 votes
2 answers
4
radha gogia asked Aug 20, 2015
381 views
int *ptr;ptr=9 ; // this is an error so to rectify it we write :int *ptr=(void*)9; why is this stmt true , what happens on type casting this 9 to a void pointer type sinc...