ProgrammingHard
A function returns a pointer to a dynamically allocated copy of its argument string. Which signature is the most correct for the caller's use?
- A. char *dup(const char *s) that returns NULL on allocation failure and expects the caller to free the result
- B. char dup(char *s) that returns the first character
- C. void dup(char *s) that copies into a global buffer of 10 bytes
- D. char *dup(const char *s) that frees s before returning
Correct answer: A. char *dup(const char *s) that returns NULL on allocation failure and expects the caller to free the result
The copy must be freed by the caller, and the result must be checked for NULL. The const parameter documents that s is not changed.
More C Programming questions
- int m = malloc(3 sizeof m); for (int i = 0; i < 3; i++) m[i] = malloc(4 sizeof m); What is the number of allocation calls made in total?
- A doubly linked list node has prev and next. What must happen before freeing the node p in the middle of the list?
- A linked stack stores nodes with a pointer to the top. Push and pop run in O(1). What is the cost of freeing the whole stack when it has n…
- A list of 10^6 nodes is built by prepending, and then each node is looked up by value in a loop. What is the total cost of 10^6 lookups?
- int p = malloc(10 sizeof p); free(p); free(p); What is the result?
- In C, which of these are true about malloc's return value (assume the request succeeds)?