[Mesa-dev] [PATCH] util: use strnlen() in strndup() implementations

Neil Roberts neil at linux.intel.com
Tue Sep 29 07:50:43 PDT 2015


Looks good to me. Thanks for doing that.

Reviewed-by: Neil Roberts <neil at linux.intel.com>

- Neil

Samuel Iglesias Gonsalvez <siglesias at igalia.com> writes:

> If the string being copied is not NULL-terminated the result of
> strlen() is undefined.
>
> Signed-off-by: Samuel Iglesias Gonsalvez <siglesias at igalia.com>
> ---
>  src/util/ralloc.c  | 5 +----
>  src/util/strndup.c | 6 ++----
>  2 files changed, 3 insertions(+), 8 deletions(-)
>
> diff --git a/src/util/ralloc.c b/src/util/ralloc.c
> index 01719c8..e07fce7 100644
> --- a/src/util/ralloc.c
> +++ b/src/util/ralloc.c
> @@ -359,10 +359,7 @@ ralloc_strndup(const void *ctx, const char *str, size_t max)
>     if (unlikely(str == NULL))
>        return NULL;
>  
> -   n = strlen(str);
> -   if (n > max)
> -      n = max;
> -
> +   n = strnlen(str, max);
>     ptr = ralloc_array(ctx, char, n + 1);
>     memcpy(ptr, str, n);
>     ptr[n] = '\0';
> diff --git a/src/util/strndup.c b/src/util/strndup.c
> index 2c24d37..5ceb32f 100644
> --- a/src/util/strndup.c
> +++ b/src/util/strndup.c
> @@ -23,6 +23,7 @@
>  
>  #if defined(_WIN32)
>  #include <stdlib.h>
> +#include <string.h>
>  #include "strndup.h"
>  
>  char *
> @@ -34,10 +35,7 @@ strndup(const char *str, size_t max)
>     if (!str)
>        return NULL;
>  
> -   n = strlen(str);
> -   if (n > max)
> -      n = max;
> -
> +   n = strnlen(str, max);
>     ptr = (char *) calloc(n + 1, sizeof(char));
>     if (!ptr)
>        return NULL;
> -- 
> 2.1.4
>
> _______________________________________________
> mesa-dev mailing list
> mesa-dev at lists.freedesktop.org
> http://lists.freedesktop.org/mailman/listinfo/mesa-dev


More information about the mesa-dev mailing list