Wednesday, 5 December 2012

Worth Read #17

Dynamic memory allocation 

Although not as common as in non-embedded computers, embedded systems do still dynamically allocate memory from the heap. What are the problems with dynamic memory allocation in embedded systems? 
Here, I expect the user to mention memory fragmentation, problems with garbage collection, variable execution time, and so on. the question is,
What does the following code fragment output and why?

char *ptr;
if ((ptr = (char *)malloc(0)) == NULL)
else
puts("Got a null pointer");
puts("Got a valid pointer");

This is a fun question. I stumbled across this only recently when a colleague of mine inadvertently passed a value of 0 to malloc and got back a valid pointer! That is, the above code will output "Got a valid pointer." interviewer use this to start a discussion on whether the interviewee thinks this is the correct thing for the library routine to do. Getting the right answer here is not nearly as important as the way you approach the problem and the rationale for your decision.

No comments:

Post a Comment