Search code examples
cvalgrind

what is Valgrind error overlap in strcpy?


I am facing this error I never have faced using valgrind do you guys have any input. I am new to C and still learning. Thank you!

This is below the error I got using valgrind.

==8410== Source and destination overlap in strcpy(0xfff000560, 0xfff000560)
==8410==    at 0x4C2E272: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8410==    by 0x40126B: trim (in /********/********/********/private/********/********/********/calls)
==8410==    by 0x40154B: main (in /********/********/********/private/********/********/********/calls)
==8410==
==8410== Source and destination overlap in strcpy(0xfff000560, 0xfff000560)
==8410==    at 0x4C2E272: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8410==    by 0x40126B: trim (in /********/********/********/private/********/********/********/calls)
==8410==    by 0x4016C6: main (in /********/********/********/private/********/********/********/calls)
==8410==
==8410==
==8410== HEAP SUMMARY:
==8410==     in use at exit: 0 bytes in 0 blocks
==8410==   total heap usage: 30 allocs, 30 frees, 1,288 bytes allocated
==8410==
==8410== All heap blocks were freed -- no leaks are possible
==8410== For counts of detected and suppressed errors, rerun with: -v
==8410== ERROR SUMMARY: 19 errors from 2 contexts (suppressed: 0 from 0)

my method

static char *trim(char *s)
{
    int i;
    for (i = 0; isspace(s[i]); i++)    // skip leading
        ;
    int from = i;    // start here
    
    for (; s[i]; i++)    // move until end
        ;

    // move backwards, skip trailing
    for (i--; i>from && isspace(s[i]); i--)
        ;
    s[i+1] = '\0';    // stop here

    strcpy(s, &s[from]);    // copy this part to beginning
          
    return s;
}

Solution

  • Changed this line

    strcpy(s, &s[from]);
    

    To

                        //# of characters
    memmove(s, &s[from], i - from + 1);