C++ Logo

sg12

Advanced search

[ub] Undefined behaviour from uninitialised variables

From: Christopher Jefferson <chris_at_[hidden]>
Date: Thu, 31 Oct 2013 09:16:15 +0000
Me and my wife teach C and C++ at Scottish Universities. I asked her
what is the most important bit of UB she would like to see removed to
make C++ easier to teach. Her suggestion (which I agree with) is how
easy it is to no initialise variables, both in classes and on the
stack. There are 2 main current ways I am aware of detecting UB from
uninitalised variables:

1) Many compilers warn about stack variables being read before they
are written to, with an appropriate warning level (but none provide
these warnings with no warning flag, and some deductions require
optimisation, which then means you have to compile twice to get a
debugging version)

2) Tools like 'valgrind' will warn of more variable misuses.

However, Rightly or wrongly, students will not use these tools
correctly, and will get difficult to fix bugs.

Her suggested fix is to introduce a new notation for constructors
which means "I am not initialising this member on purpose". This will
allow compilers to then add a warning at a high warning level that a
member is missed from a constructor.

I also wonder, what is people's opinion on telling students from day 1
of a C++ class to always run their programs through valgrind, even
their first "hello world" program? This would help them catch a much
wider range of bugs earlier, but also teaches them a safety net they
may come to excessively rely on.

Chris

Received on 2013-10-31 10:16:16