cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

gcc warnings that are emitted only when optimizations are enabled

Open cgkantidis opened this issue 2 years ago • 1 comments

Channel

This is a C++Weekly episode

Topics

While working on some production code today, I saw a warning, but when I tried to reproduce it, it wasn't emitted.

It turns out that the warning is emitted only when -O2 or higher level of optimization is enabled, which blew my mind.

Since you always mention that code should be tested both with optimization on and off, I think it's good to add this as an example.

Example:

main.cpp

#include <cstring>

void my_copy(char const *s) {
    char buf1[64];
    char buf2[64];
    strncpy(buf1, s, 64);
    strncpy(buf2, buf1, 63);
}

int main(int argc, char **argv) {
    if (argc != 2) {
        return 1;
    }

    my_copy(argv[1]);
    return 0;
}
g++ -Wall -O1 main.cpp
// no output
g++ -Wall -O2 main.cpp
main.cpp: In function ‘void my_copy(const char*)’:
main.cpp:6:12: warning: ‘char* strncpy(char*, const char*, size_t)’ specified bound 64 equals destination size [-Wstringop-truncation]
    6 |     strncpy(buf1, s, 64);
      |     ~~~~~~~^~~~~~~~~~~~~
main.cpp:7:12: warning: ‘char* strncpy(char*, const char*, size_t)’ output may be truncated copying 63 bytes from a string of length 63 [-Wstringop-truncation]
    7 |     strncpy(buf2, buf1, 63);
      |     ~~~~~~~^~~~~~~~~~~~~~~~

Length

This should be a short video, 10 minutes tops.

cgkantidis avatar Mar 10 '23 16:03 cgkantidis

These topics often come up during training classes. Should make a good episode.

lefticus avatar Mar 10 '23 20:03 lefticus