You are copying pointers to the strings, not the strings themselves. You should change your for
loop to
for(i = startIndex; i < endIndex; i++) {
childWords[i] = strdup(words[i]); // creates a new copy of the string
}
strdup
duplicates the string by allocating enough memory to copy the string passed to it, i.e., it returns a pointer to a new string which is a duplicate of the string pointed to by words[i]
. The pointer can be passed to free
. It's declared in the string.h
header file.
Please note that you should not cast the result of malloc
. There's no benefit and it can lead to bugs if you forget to include the stdlib.h
header file. Also strdup
is a part of the POSIX standard and under the hood, it effectively does the same thing as malloc
and then strcpy
. Read more here What does strdup do?