118 views

### *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??

retagged | 118 views

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.

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.

1
2