Pointer initialisation gives segmentation fault

后端 未结 5 648
刺人心
刺人心 2020-12-03 04:09

I wrote a C program as follows:

CASE 1

int *a; /* pointer variable declaration */

int b; /* actual variable declaration */

*a=11;

a=&b;/* st         


        
5条回答
  •  星月不相逢
    2020-12-03 04:28

    int *a; // a pointer variable that can hold a memory address of a integer value.
    

    In case 1,

      *a = 10; // here you have asigned 10 to unknown memory address;
    

    It shows segmentation fault because of assigning value to a memory address that is not defined. Undefined behaviour.

    In case 2,

    a=&b; // assigning a proper memory address to a.
    *a=11;// assigning value to that address
    

    Consider this example:

    #include
    int main()
    {
       int *a,b=10;
       printf("\n%d",b);
       a=&b;
       *a=100;
       printf("-->%d",b);
    }
    
    Output: 10-->100
    

    Here this is how it works.

             b        // name
         ----------
         +   10   +   // value
         ---------- 
            4000      // address 
    

    Asuuming memory location of b is 4000.

    a=&b => a=4000;
    *a=100 => *(4000)=100 => valueat(4000) => 100
    

    After manipulation it looks like this.

             b        // name
         ----------
         +  100   +   // value
         ---------- 
            4000      // address 
    

提交回复
热议问题