23.03.2017 Views

SEI CERT C++ Coding Standard

sei-cert-cpp-coding-standard-2016-v01

sei-cert-cpp-coding-standard-2016-v01

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Memory Management (MEM) - MEM51-CPP. Properly deallocate dynamically allocated resources<br />

7.2.6 Compliant Solution (Double-Free)<br />

In this compliant solution, the copy constructor and copy assignment operator for C are explicitly<br />

deleted. This deletion would result in an ill-formed program with the definition of g() from the<br />

preceding noncompliant code example due to use of the deleted copy constructor. Consequently,<br />

g() was modified to accept its parameter by reference, removing the double-free.<br />

struct P {};<br />

class C {<br />

P *p;<br />

public:<br />

C(P *p) : p(p) {}<br />

C(const C&) = delete;<br />

~C() { delete p; }<br />

void operator=(const C&) = delete;<br />

void f() {}<br />

};<br />

void g(C &c) {<br />

c.f();<br />

}<br />

void h() {<br />

P *p = new P;<br />

C c(p);<br />

g(c);<br />

}<br />

7.2.7 Noncompliant Code Example (array new[])<br />

In the following noncompliant code example, an array is allocated with array new[] but is<br />

deallocated with a scalar delete call instead of an array delete[] call, resulting in undefined<br />

behavior.<br />

void f() {<br />

int *array = new int[10];<br />

// ...<br />

delete array;<br />

}<br />

<strong>SEI</strong> <strong>CERT</strong> <strong>C++</strong> CODING STANDARD (2016 EDITION) | V01 225<br />

Software Engineering Institute | Carnegie Mellon University<br />

[DISTRIBUTION STATEMENT A] Approved for public release and unlimited distribution.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!