I have 3 questions regarding the following function. I marked them as comments in code.
-
Why do we copy char item pointed by
dest(malloced memory) todPtr, and then in the end (after processing the input string)return dest. Wouldn’t it be simpler to operate ondest. -
This function basically reverses the word only if it has dashes inside. Does the marked command
*subword = '\0';put aNULcharacter at the place of previously incremented place (instrncpy) –subword+1or in thesubword? -
Is this function prone to some buffer overflows or other undesired behaviour? Now it doesn’t give me any errors, but I think I just don’t know how to debug it.
len is strlen(word)
char* function(char* word, int len)
{
char* subword = NULL;
char* dest;
char* dPtr;
size_t n;
dest = malloc(len+1);
if (dest == NULL) return NULL;
dPtr = dest; /* [1] */
while((subword = strrchr(word, '-'))!= NULL) {
n = len - (subword-word) - (dPtr-dest);
if (n-1 > 0)
strncpy(dPtr, subword+1, n-1);
*subword = '\0'; /* [2] */
dPtr += n-1;
*dPtr = '-';
dPtr++;
}
strncpy(dPtr, word, len - (dPtr-dest));
dest[len] = '\0';
return dest; /* [1] */
}
dPtris being used to move through the string and modify it.destis being kept as the beginning of that modified string, eventually the return value of the function. At the end of each loop iteration,dPtrwill point to the end of the modified string, and used for each successivestrncpy. Ultimately the function returns a modified string, anddestis needed to keep track of it’s beginning.subwordis being null terminated presumably so that only characters insubwordwill be copied into the result in thestrncpywithin the loop, but this actually isn’t necessary with the use ofstrncpy. The function moves backwards through the string looking for dashes. For each hit,subwordis the next dash-delimited substring. The substring is a piece of memory inside the original string, which isn’t null-terminated. If you were usingstrcpythen you’d need null-termination ofsubword, but since you’re usingstrncpythe null-terminators shouldn’t be necessary: just be careful with yournvalues as thestrncpylimit. This code null-terminatessubwordin place, i.e. by sticking null characters inside the original string argument. Which leads to #3:As for undesired behavior, the function does it’s work by modifying the original string argument – it’s putting those null terminators for
subwordinto the source string – even though it’s keeping it’s own buffer for the modified and returned string.Finally, the code could do without
dPtrby usingstrncatoperations rather thanstrncpy.