mirror of https://github.com/kgabis/parson.git
Avoid truncating strings warning (#131)
* Avoid truncating strings warning GCC 8 introduced the `stringop-truncation` warning, which warns for uses of `strncpy` of the form `strncpy(out, in, strlen(in))`. This is often helpful, as this call would not copy the trailing `\0`, potentially leading to subtle bugs. With optimizations enabled, the function `parson_strndup` is inlined, allowing the compiler to see that this call to `strncpy` is of the form described above. GCC therefore outputs the warning. In this case, the out buffer has already had the terminating `\0` written to the end. Thus it is not necessary to copy it. GCC 9.2 is not quite smart enough to recognize this, so it warns. The warning is silenced by using `memcpy` instead of `strncpy`. Although I have not benchmarked it, this change might reasonably improve the performance of `parson_strndup`. `strncpy` checks every byte for `\0` in addition to counting to `n`. `memcpy` does not need to check whether the bytes it copies are `\0`. However, if `parson_strndup` is frequently passed `char *`s with a `\0` somewhere in the middle, then `memcpy` will copy more bytes than necessary, hurting performance. In this case, a better solution might be: ``` - output_string[n] = `\0`; - strncpy(output_string, string, n); + strncpy(output_string, string, n+1); ``` * Increments parson's version.pull/133/head
parent
0341880552
commit
9d63e76014
Loading…
Reference in new issue