Error checks like
if ((!str) || (!*str))
andif ((start_index < 0) || (end_index < 0) || (end_index < start_index))
etc don't belong inside a library function. It's the caller's responsibility to do these checks on the caller side. Also some of these checks are just there because you picked an unsuitable integer typelong
instead of an unsigned type.I'd say that the checks after the
strlen
call are ok though.If you place the checks inside a library function, then the needless extra branches lag down normal use with correct parameters passed.
long start_index, long end_index
would be more appropriate assize_t
since we are ultimately dealing with indices of an array. Same thing elsewhere in the function, replacelong
withsize_t
. That way you get rid of the casts too.memmove
should bememcpy
since there is no risk of overlap here andmemcpy
is faster.There are already very similar functions
strstr
+strdup
orstrndup
where the dup ones are not yet standard C but looks like they will get added to the standard in the upcoming C23 version. So there's no obvious need to re-invent the wheel.
↧
Answer by Lundin for substr() function, not present in standard C library
↧