lefticus / cpp_weekly

The official C++ Weekly Repository. Code samples and notes of future / past episodes will land here at various times. PR's will be accepted in some cases.
The Unlicense
698 stars 26 forks source link

gcc warnings that are emitted only when optimizations are enabled #262

Open christosg88 opened 1 year ago

christosg88 commented 1 year ago

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.

lefticus commented 1 year ago

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