GATE CSE
First time here? Checkout the FAQ!
x
0 votes
80 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 (5.5k points)   | 80 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.5k 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 Feb 2017
  1. Arjun

    5396 Points

  2. Bikram

    4230 Points

  3. Habibkhan

    3952 Points

  4. Aboveallplayer

    3086 Points

  5. Debashish Deka

    2564 Points

  6. sriv_shubham

    2318 Points

  7. Smriti012

    2240 Points

  8. Arnabi

    2008 Points

  9. mcjoshi

    1696 Points

  10. sh!va

    1684 Points

Monthly Topper: Rs. 500 gift card

20,863 questions
26,023 answers
59,698 comments
22,136 users