GATE CSE
First time here? Checkout the FAQ!
x
0 votes
93 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 (6.6k points)   | 93 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 May 2017
  1. akash.dinkar12

    3338 Points

  2. pawan kumarln

    2066 Points

  3. Bikram

    1922 Points

  4. sh!va

    1672 Points

  5. Arjun

    1614 Points

  6. Devshree Dubey

    1272 Points

  7. Debashish Deka

    1174 Points

  8. Angkit

    1056 Points

  9. LeenSharma

    1018 Points

  10. Arunav Khare

    758 Points

Monthly Topper: Rs. 500 gift card
Top Users 2017 May 22 - 28
  1. Bikram

    1008 Points

  2. pawan kumarln

    692 Points

  3. Arnab Bhadra

    632 Points

  4. Arjun

    342 Points

  5. bharti

    328 Points


22,888 questions
29,193 answers
65,292 comments
27,691 users