Prevent structs from being uninitialized in C++

Viewed 89

Here's three files in which the first has a bug:

// main.cpp
#include <iostream>
#include "lib.h"


int main() {
    Deposit d; // Bug! Needs to be Deposit d = {};
    d.dollars = 3;
    // std::cout << reconfigure_params.version; // We do get an error here..
    run(&d);
    return 0;
}
// lib.cpp
#include <iostream>
#include "lib.h"

void run(Deposit* d) {
        std::cout << "Depositing " << d->dollars << " dollars and " << d->cents << " cents " << std::endl;
}
// lib.h
typedef struct _Deposit {
        int dollars;
        int cents;
} Deposit;


void run(Deposit* d);

How do I use GCC or some tool like clang-tidy or cppcheck to warn me about this bug?

Things I've tried:

$ g++ -c   -pedantic -Wall -Wextra -Wcast-align -Wcast-qual -Wctor-dtor-privacy -Wdisabled-optimization -Wformat=2 -Winit-self -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs -Wnoexcept -Wold-style-cast -Woverloaded-virtual -Wredundant-decls -Wshadow -Wsign-conversion -Wsign-promo -Wstrict-null-sentinel -Wstrict-overflow=5 -Wswitch-default -Wundef -Werror -Wno-unused lib.cpp
$ g++   -pedantic -Wall -Wextra -Wcast-align -Wcast-qual -Wctor-dtor-privacy -Wdisabled-optimization -Wformat=2 -Winit-self -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs -Wnoexcept -Wold-style-cast -Woverloaded-virtual -Wredundant-decls -Wshadow -Wsign-conversion -Wsign-promo -Wstrict-null-sentinel -Wstrict-overflow=5 -Wswitch-default -Wundef -Werror -Wno-unused lib.o main.cpp
=> No error
cppcheck --enable=all main.cpp
=> No error

I did notice when I ran cppcheck --enable all * I did get an error. I'm not sure how that works, but a more fair test would be to not have access to the lib source. That is, assume that lib is a compiled binary.

I hope this doesn't seem contrived. I ran into this precise issue with some NVIDIA code that took several days to track down. I'm hoping to prevent issues like this in the future.

Thanks!

0 Answers
Related