Microsoft Interview Question
Software Engineer / DevelopersTeam: bing
Country: India
Interview Type: In-Person
node points to first byte of address.
but shouldn't this be
List* node;
--- node=malloc(sizeof(node));
+++ node=malloc(sizeof(LIST));
because when you allocate using sizeof(node) it will returns size of address and not the complete struct size. and when we try to write we might get into segmentation faults.
List* node;
node=malloc(sizeof(node));
.........
above statement will give error:
cannot convert from 'void *' to List*
malloc return void* pointer to location where memory is allocated
correction:
List* node;
node=(node*)malloc(sizeof(node));
I think the implicit void conversion does work in plain old C, and doesn't work in C++.
when using malloc, it returns void type. we need to type cast. And the acutall memory allocated is larger than you applied, the first part stores the number of bytes allocated (offset to teh next memory from the start of this memroy). For example, if you do int *i = (int*) malloc(12), it allocates 16 bytes. The first 4 bytes for actuall size, from 5th byte is return to i, now i can acess 12 bytes from this byte.
when using malloc, it returns void type. we need to type cast. And the acutall memory allocated is larger than you applied, the first part stores the number of bytes allocated (offset to teh next memory from the start of this memroy). For example, if you do int *i = (int*) malloc(12), it allocates 16 bytes. The first 4 bytes for actuall size, from 5th byte is return to i, now i can acess 12 bytes from this byte.
- lliyanc March 26, 2012