Hello,
I am getting ready for an interview, and am going over some interview questions.
I am looking for a second opinion on one of the questions. Before anyone says this is cheating, I have worked the question through - including writing up and running the code snippet - and I am reasonably confident I've got it right.
Now - here's what's bugging me: the question is presented as a "Is there anything wrong with this code?" question.
In my experience, I've never once found an "Is there anything wrong with this?" question in which there is not actually something wrong.
Well, I've been through it, and I can't find anything wrong with it - it compiles and runs fine. As far as what it is supposed to do, I can't find anything wrong with this either, since its just an example test question - it doesn't 'do' anything.
Here's the question - along with my response. A second opinion would be greatly appreciated.
Thanks in advance,
Tim
DEF *CreateDEF (void)
{
DEF *p = (DEF*)malloc(sizeof(DEF) + sizeof(ABC));
p->abc = (ABC *)((char *)p + sizeof(DEF));
return p;
}
2. Is the following code OK? What does it do?
(1) DEF *pdef = CreateDEF();
(2) int value;
(3) value = (int) pdef;
(4) value += 8;
(5) *(int *) value = 10;
//My response:
Line (1) - allocates memory for a DEF structure and returns a pointer to this area in memory.
It does not assign values to the d, e, or f integers; or the a, b, or c integers.
Line (2) - just declares an integer named 'value' without assigning a value to it.
Line (3) - the integer 'value' is assigned the address in memory that pdef points to.
Line (4) - the value of 'value' is increased by 8 - or 8 bits of memory.
Line (5) - the memory address of 'value' is de-referenced, and the variable that is stored
at that address, the f member variable of the DEF structure, is assigned a value of 10.
The code is OK in that it compiles without errors and runs without memory access errors.
One thing to pay attention to is that Line (4) increases a memory address by 8, which
in this case moves the address from the DEF structure's d member variable to its f member
variable.
Without Line (4) the DEF structure's d member variable is assigned a value of 10, and the
f member variable is left alone.
Start Free Trial