开发者

Shifting buffer via memcpy

I wrote following 2 ltrim functions (function which removes white-spaces from left side of the string):

1. (putting here this code to not get such code as an answer)

void 开发者_JAVA百科ltrim(char * str, int size)
{
    char const *start = str;
    char const *end = start + size;
    for(;*start && (*start==' ' || *start=='\n' || *start=='\r' || *start=='\t');++start);

    while(start != end)
    {
        *str = *start;
        ++start;
        ++str;
    }
    *str='\0';
}

2.

void ltrim(char * str, int size)
{
    char const *start = str;
    char const *end = start + size;
    for(;*start && (*start==' ' || *start=='\n' || *start=='\r' || *start=='\t');++start);
    memcpy(str, start, end-start);
    *(str + (end - start)) = '\0';
}

Does second version safe?

P.S. I have tried and it works, but not sure that memcpy is safe in this case.


When source and destination overlap you should use memmove rather than memcpy.

From the memcpy man page:

The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas should not overlap. Use memmove(3) if the memory areas do overlap.


Regarding "safe" - you missed one important case - a check that you don't overrun the buffer. Use that size parameter to bound the loop.


    memcpy(str, start, end-start);

If you memmove (see Paul R.'s answer) 1 more character, that extra character is the null terminator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜