回复: [patch] shared.c-->trim_end () Segment fault
止语
openlibrary at qq.com
Thu Apr 7 14:05:18 CEST 2011
your xstrndup() is better !
------------------
止语
------------------ 原始邮件 ------------------
发件人: "hjemli"<hjemli at gmail.com>;
发送时间: 2011年4月7日(星期四) 下午5:32
收件人: "止语"<openlibrary at qq.com>;
抄送: "cgit"<cgit at hjemli.net>;
主题: Re: [patch] shared.c-->trim_end () Segment fault
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