The following is a quote from an exam (1% top university).
I failed, because my answer differed from the "approved" answer.
I have a hunch that his (professor, known expert in C) answer is not correct.
The following, is the question followed by the "approved" answer.
There is a potential bug in the following function. What is it and how would I fix it?
Hint: this has something to do with the use of the realloc() function. Please identify the line numbers you would change and what you would replace them with.
BOOLEAN lengthen_string(char* string, const char newcontents[]) { int newlen = strlen(string) + strlen(newcontents) + 1; string = realloc(string, newlen); if (!string) { perror("malloc"); return FALSE; } strcat(string, newcontents); return TRUE; }
The "correct" answer provided by the professor was:
line 4: realloc returns a NULL pointer when it fails to allocate. This means that on failure the original data is lost.
To fix this, assign the result of realloc to a temporary variable and test that first.
Ie: line 4:
char * temp=realloc(string, newlen); if(!temp) ... (all remains the same)after old line 9,
string = temp;
Any thoughts?
BTW, my answer was that @string is a local variable, and the prototype of the function should be char **string, where the caller passes a pointer to its string pointer, and then the callee would assign any realloc() return value to *string
Any thoughts?