Yesterday in my interview I was asked this question. (At that time I was highly pressurized by so many abrupt questions).
int *p;
*p=23;
printf("%d",*p);
Is there any problem with this code?
I explained him that you are trying to assign value to a pointer to whom memory is not allocated.
But the way he reacted, it was like I am wrong. Although I got the job but after that he said Mohit think about this question again.
I don’t know what he was trying to say. Please let me know is there any problem in my answer?
EDIT
I added the code on the sheet;-
int *p;
p=malloc(sizeof(int));
*p=23;
printf("%d",*p);
This must be the perfect code…Am i right..
EDIT2
int *p;
*p=23;
OR
int *p=23;
I think both has problem. Cause some body is saying about the title of the post.
“trying to assign value to a pointer to whom memory is not allocated”
I think you just misphrased it a bit. You’re not trying to assign a value to a pointer, you’re trying to assign a value to the referand of a pointer.
Since the pointer is uninitialised, this is, as you say, undefined behaviour. The pointer doesn’t refer to anything (at least not validly – as other answers point out, the bits of storage of
pmight just so happen to contain a value which is the address of some memory location, and your code might overwrite that. The standard permits anything to happen with UB, but knowing something about your implementation you can often take a shrewd guess).So probably in the interviewer’s mind you have the right idea, but it’s valuable to have it exactly straight in your mind and in your speech what the difference is between a finger and the moon, and which one you’re talking about.