[patch] shared.c-->trim_end () Segment fault

Lars Hjemli hjemli at gmail.com
Thu Apr 7 11:32:14 CEST 2011


2011/3/30 止语 <openlibrary at qq.com>:
> From: zhongjj <zhongjj at lemote.com>
> Date: Wed, 30 Mar 2011 20:15:29 +0800
> Subject: [PATCH] to modify the action of changing a char *,or it would cause
>  Segment fault !
> ---
>  shared.c |    9 ++-------
>  1 files changed, 2 insertions(+), 7 deletions(-)
>
> diff --git a/shared.c b/shared.c
> index 7ec2e19..f26477b 100644
> --- a/shared.c
> +++ b/shared.c
> @@ -100,11 +100,9 @@ void *cgit_free_commitinfo(struct commitinfo *info)
>  char *trim_end(const char *str, char c)
>  {
>    int len;
> -   char *s, *t;
> -
>    if (str == NULL)
>        return NULL;
> -   t = (char *)str;
> +    char *t = xstrdup(str);
>    len = strlen(t);
>    while(len > 0 && t[len - 1] == c)
>        len--;
> @@ -112,11 +110,8 @@ char *trim_end(const char *str, char c)
>    if (len == 0)
>        return NULL;
>
> -   c = t[len];
>    t[len] = '\0';
> -   s = xstrdup(t);
> -   t[len] = c;
> -   return s;
> +   return t;
>  }
>
>  char *strlpart(char *txt, int maxlen)

Thanks, good catch. But maybe we should use xstrndup(), e.g. like this:

@@ -100,23 +100,16 @@ void *cgit_free_commitinfo(struct commitinfo *info)
 char *trim_end(const char *str, char c)
 {
        int len;
-       char *s, *t;

        if (str == NULL)
                return NULL;
-       t = (char *)str;
-       len = strlen(t);
-       while(len > 0 && t[len - 1] == c)
+       len = strlen(str);
+       while(len > 0 && str[len - 1] == c)
                len--;

        if (len == 0)
                return NULL;
-
-       c = t[len];
-       t[len] = '\0';
-       s = xstrdup(t);
-       t[len] = c;
-       return s;
+       return xstrndup(str, len);
 }

--
larsh




More information about the CGit mailing list