I have some second thoughts about the following C puzzle question. I'm curious what more experience C programmers may think... Have a look at the sample code:
char * strdup (const char * s) {
char * buf;
int len;
assert(s != NULL);
len = strlen(s);
buf = (char *) calloc(len + 1, sizeof(char));
memcpy(buf, s, len);
return buf;
}
The proposed implementation of strdup() above contains a runtime error that may NOT appear consistently with each invocation. Which one of the following accurately describes this error?
The possible answers to this one are:
1 The arguments to calloc() do not cause enough memory to be allocated for storing the contents of s.
2 If memory is scarce, calloc() may fail and return NULL. The code does not anticipate this condition.
3 memcpy() may corrupt data if used to copy ASCII strings.
4 buf is never NUL-terminated, and therefore cannot be used by C library functions affecting strings.
5 The function returns a pointer to dynamic memory. This practice should be avoided and always constitutes a memory leak.
What I've thought is that the correct answer is 2 but it is more because the other answers seem incorrect to me than because answer 2 is the immediate right one.
answer 1 seems incorrect as calloc reserves enough memory (len+1) to end the string appropriately,
I dont know anything about what is written in answer 3,
answer4: memcpy copies the content of s to buf leaving the last byte equal to 0 (copies len bytes, note that previos call to calloc filled the last byte with 0). Therefore, this answer is incorrect,
answer 5: ?
What do you think? Thanks in advance...
Correct answer is 2 & 5.
#2
because memory allocation functions can fail and you must check their return values.
#5
because, unless you document the fact that your function dynamically allocates returned buffer caller cannot know that they have to free the returned buffer.
#1
is not correct because, as you rightly said calloc
allocates memory required by string + extra byte required for NULL
termination.
#3
is not correct because it is not true, memcpy
simply copies data from source to destination. It is not affected by what is stored in that memory.
#4
is not correct, because calloc
zeroes out the allocated memory.