From 2f9370afe7d07307f636a2473348c2e17de59a9c Mon Sep 17 00:00:00 2001 From: Robert James Kaes Date: Thu, 13 Mar 2003 05:20:06 +0000 Subject: (chomp): Fixed up the code to prevent negative array access. Added code to make sure the supplied arguments are valid. --- src/text.c | 18 ++++++++++++------ src/text.h | 4 ++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/text.c b/src/text.c index 0c6c875..1db568b 100644 --- a/src/text.c +++ b/src/text.c @@ -1,4 +1,4 @@ -/* $Id: text.c,v 1.2 2002-05-24 04:45:32 rjkaes Exp $ +/* $Id: text.c,v 1.3 2003-03-13 05:20:06 rjkaes Exp $ * * The functions included here are useful for text manipulation. They * replace or augment the standard C string library. These functions @@ -75,24 +75,30 @@ strlcat(char *dst, const char *src, size_t size) * "length" should be the number of characters in the buffer, not including * the trailing NULL. * - * Returns the number of characters removed from the end of the string. + * Returns the number of characters removed from the end of the string. A + * negative return value indicates an error. */ -size_t +ssize_t chomp(char *buffer, size_t length) { size_t chars; assert(buffer != NULL); + assert(length > 0); + + /* Make sure the arguments are valid */ + if (buffer == NULL) return -EFAULT; + if (length < 1) return -ERANGE; chars = 0; --length; while (buffer[length] == '\r' || buffer[length] == '\n') { - buffer[length--] = '\0'; + buffer[length] = '\0'; chars++; - if (length < 0) - break; + /* Stop once we get to zero to prevent wrap-around */ + if (length-- == 0) break; } return chars; diff --git a/src/text.h b/src/text.h index fd0940a..946adbd 100644 --- a/src/text.h +++ b/src/text.h @@ -1,4 +1,4 @@ -/* $Id: text.h,v 1.1 2002-05-23 04:42:30 rjkaes Exp $ +/* $Id: text.h,v 1.2 2003-03-13 05:20:06 rjkaes Exp $ * * See 'text.c' for a detailed description. * @@ -26,6 +26,6 @@ extern size_t strlcat(char *dst, const char *src, size_t size); extern size_t strlcpy(char *dst, const char *src, size_t size); #endif /* HAVE_STRLCPY */ -extern size_t chomp(char *buffer, size_t length); +extern ssize_t chomp(char *buffer, size_t length); #endif -- cgit v1.2.3