Given the function definition:
int mallocPlusStrcpy(const char* src, char* dst)
which should take in a char*, which may be null or may or may not otherwise be populated with data, allocate a new char* dst of appropriate length, correctly copy the string, and return the number of bytes copied.
What is wrong with this function definition? Provide a corrected function definition.
——————————————————-
Given the function definition:
int mallocPlusStrcpy(const char* src, char* dst)
which should take in a char*, which may be null or may or may not otherwise be populated with data, allocate a new char* dst of appropriate length, correctly copy the string, and return the number of bytes copied.
With your correction to the function definition above, provide pseudocode describing the mallocPlusStrcpy function.
Expert Answer
The answer to the question is given below. Please rate the answer if it helped. Thank you.
Since we want to modify the dst pointer and the changes should be available in the calling function, we need to pass the
address of *dst. So the function signature should use char** dst instead of char *dst.
The definition of the function would look like
int mallocPlusStrcpy(const char* src, char** dst)
{
int len = 0;
if(src == NULL)
{
*dst = NULL;
}
else
{
len = strlen(src);
*dst =(char*) malloc(len + 1); //length of string plus 1 for null terminator
strcpy(*dst, src);
}
return len;
}