Quantcast
Channel: User Lundin - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 42

Answer by Lundin for substr() function, not present in standard C library

$
0
0
  • Error checks like if ((!str) || (!*str)) and if ((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 type long 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 as size_t since we are ultimately dealing with indices of an array. Same thing elsewhere in the function, replace long with size_t. That way you get rid of the casts too.

  • memmove should be memcpy since there is no risk of overlap here and memcpy is faster.

  • There are already very similar functions strstr+strdup or strndup 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.


Viewing all articles
Browse latest Browse all 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>