GATE CSE
First time here? Checkout the FAQ!
x
0 votes
141 views

char *p;

*p='a' ;

 

I know this will give compiler error but can anyone explain what is the actual bug in this and how to rectify it??

asked in Programming by Boss (7.4k points)  
retagged by | 141 views

1 Answer

0 votes
char *p;
*p = 'a'; //Till here no problem
printf("%c",*p); //This is problem

By declaring char pointer we have not initialized so it must be pointing to some random address.

Now if we try to access a random location we will end up with undefined behaviour as random address may work fine also but what if the random address belongs to some other process address space then we will get a segmentation fault. So its good practice to initialize the pointers.

Also we won't have compile time error rather run time error.

answered by Loyal (3.7k points)  
but what does *p='a' does actually?? i mean isnt 'a' first created in some memory location and then address assigned to p??
you are assigning a character value not character address.

correct steps are :

char ch = 'a';

char *p = &ch;
sorry it was a typo.

what if i write  char *ch=&('a');

it will give compiler error right??
definately its an compile time error.

@Gate mission 1,

so what does statement 

char *p;
*p = 'a'; actually doing??
It is accessing some random memory location which we don't know about and can result in segmentation fault or trap.


Top Users Sep 2017
  1. Habibkhan

    6362 Points

  2. Warrior

    2234 Points

  3. Arjun

    2212 Points

  4. nikunj

    1980 Points

  5. manu00x

    1726 Points

  6. SiddharthMahapatra

    1718 Points

  7. Bikram

    1716 Points

  8. makhdoom ghaya

    1660 Points

  9. A_i_$_h

    1528 Points

  10. rishu_darkshadow

    1512 Points


25,988 questions
33,561 answers
79,406 comments
31,026 users