Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined Behavior: A checklist for code reviews [duplicate]

Possible Duplicate:
What are all the common undefined behaviour that a C++ programmer should know about?

I am about to prepare a checklist or guideliness for C++ self & peer code reviews, Since there are so many scenarios which may lead to realm of the dreaded Undefined Behavior, I was thinking of coming up with a sort of checklist of Undefined behaviors in most heavily used C++ language constructs.

Ofcourse it is not possible to anticipate the Undefined behaviors which emnate through modifications of variables between Sequence points but I think it is possible to list down scenarios emnating from other scenarios.

If you were performing a code review what commonly Undefined Behavior producing scenarios would you look out for?

like image 580
Alok Save Avatar asked Jun 07 '11 03:06

Alok Save


2 Answers

(1) Bad delete

T* p = new T[N];
delete p; // ...1
delete (p+x); //...2

(2) Missing return

int* foo ()
{
  // code
  return p;
  // code
}

(3) Double delete

(4) Reference to temporary

(5) Adding vector element to itself (when size was defined)

  vector<int> vi(1);
  vi.push_back(0);
  vi.push_back(vi[0]); // it can become a use case of pt(4) (sometimes)
like image 101
iammilind Avatar answered Oct 23 '22 14:10

iammilind


Non-Availability of Virtual Destructor in polymorphic base class

Trivial Example

class Base
{
   public:
    Base();
   // some virtual functions     
   // no virtual destructor
   ~Base();
};

class Derived : public Base
{
   public:
   Derived();
   // override the functions here      
   ~Derived();
};
// definitions
int main()
{
   Base *p = new Derived();
   // function calls
   delete p; // UB
}

Here is a comprehensive list of undefined behaviour scenarios in C++.

like image 33
Prasoon Saurav Avatar answered Oct 23 '22 13:10

Prasoon Saurav