Search code examples
cgccgcc4

Can't figure out why this trimming function won't work correctly


===============================================================================

void trim(const char * orig, char * dest)
{
    size_t front = 0;
    size_t end = sizeof(orig) - 1;
    size_t counter = 0;
    char * tmp = null;

    if (sizeof(orig) > 0)
    {
        memset(dest, '\0', sizeof(dest));

        /* Find the first non-space character */
        while (isspace(orig[front]))
        {
                front++;
        }
        /* Find the last non-space character */
        while (isspace(orig[end]))
        {
                end--;
        }

        tmp = strndup(orig + front, end - front + 1);
        strncpy(dest, tmp, sizeof(dest) - 1);
        free(tmp); //strndup automatically malloc space
    }
}

===============================================================================

I have a string:

'     ABCDEF/G01        '

The above function is supposed to remove the spaces and return to me:

'ABCDEF/G01'.

Instead, what I get back is:

'ABCDEF/'

Any ideas?

Note: the quotes are just to show you that spaces exist in the original string.


Solution

  • The strncpy is wrong. sizeof(dest) is not what you want (it's the size of a pointer on your machine). You probably want: end - front. Instead, try:

    memcpy(dest, front + start, end - front);
    dest[end] = 0;