Mihran Hovsepyan
Mihran Hovsepyan

Reputation: 11098

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 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.

Upvotes: 5

Views: 6032

Answers (3)

pmg
pmg

Reputation: 108938

    memcpy(str, start, end-start);

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

Upvotes: 0

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84189

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

Upvotes: 0

Paul R
Paul R

Reputation: 212979

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.

Upvotes: 14

Related Questions