Hi, On Fri, Aug 15, 2025 at 3:48 AM Thorsten Blum <[email protected]> wrote: > > Hi Doug, > > On 15. Aug 2025, at 04:05, Doug Anderson wrote: > > Let's think about some test cases... > > > > Old code: > > mp->usage = kdb_strdup(argv[2], GFP_KDB); > > if (mp->usage[0] == '"') { > > strcpy(mp->usage, argv[2]+1); > > mp->usage[strlen(mp->usage)-1] = '\0'; > > } > > > > New code: > > mp->usage = kdb_strdup(argv[2], GFP_KDB); > > if (mp->usage[0] == '"') > > strscpy(mp->usage, argv[2] + 1, strlen(argv[2]) - 1); > > > > Example string: argv[2] = "\"xyz\"" > > > > Old: > > mp->usage = strdup("\"xyz\"") > > mp->usage becomes "xyz\"" > > mp->usage becomes "xyz" > > > > New: > > mp->usage = strdup("\"xyz\"") > > mp->usage becomes "xyz\"" > > mp->usage doesn't change (!) > > > > To match old behavior, I think you'd need "strlen(argv[2]) - 2", right? > > No, it should be "strlen(argv[2]) - 1" to match the old behavior. > > In the new code, there are only two steps instead of three. > > With your example source string "\"xyz\"" in argv[2]: > > strscpy(mp->usage, argv[2] + 1, strlen(argv[2]) - 1) > > evaluates to: > > strscpy(mp->usage, "xyz\"", strlen("\"xyz\"") - 1) > > strlen("\"xyz\"") is 5, so this becomes: > > strscpy(mp->usage, "xyz\"", 4) > > Unlike strcpy(), strscpy() copies at most 'size - 1' characters and then > appends a NUL terminator. In the example, it copies only the first three > bytes (xyz) and then appends a NUL terminator, effectively replacing the > trailing quote. The result is "xyz", the same as before.
Ugh, I missed that strscpy() implicitly takes away an extra character. So, yes, your version does appear correct in that sense. It's definitely non-obvious and I agree with Daniel that it doesn't feel like the right way to use strscpy(). -Doug
