GATE CSE
First time here? Checkout the FAQ!
x
0 votes
60 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 Loyal (4.6k points)   | 60 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.3k 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 Jan 2017
  1. Debashish Deka

    7172 Points

  2. Habibkhan

    4696 Points

  3. Vijay Thakur

    4308 Points

  4. sudsho

    4090 Points

  5. saurabh rai

    4024 Points

  6. Arjun

    3292 Points

  7. santhoshdevulapally

    3066 Points

  8. GateSet

    3016 Points

  9. Bikram

    3014 Points

  10. Sushant Gokhale

    2892 Points

Monthly Topper: Rs. 500 gift card

18,838 questions
23,808 answers
51,588 comments
20,148 users