...
Code Block |
---|
|
#include <new>
struct S {
void f();
};
void f() noexcept(false) {
S *s = new S;
// ...
delete s;
// ...
s->f();
}
|
The function f()
is marked noexcept(false)
to comply with MEM32-CPP. Detect and handle memory allocation errors.
Compliant Solution (new
and delete
)
...
Code Block |
---|
|
#include <new>
struct S {
void f();
};
void f() noexcept(false) {
S *s = new S;
// ...
s->f();
delete s;
} |
...
Code Block |
---|
|
#include <iostream>
#include <memory>
#include <cstring>
int main(int argc, const char *argv[]) {
const char *s = "";
if (argc > 1) {
enum { BUFFER_SIZE = 32 };
try {
std::unique_ptr<char[]> buff (new char[BUFFER_SIZE]);
// ...
s = std::strncpy(buff.get(), argv[1], BUFFER_SIZE - 1);
} catch (std::bad_alloc &) {
// Handle error
}
}
std::cout << s << std::endl;
}
|
...
Code Block |
---|
|
#include <iostream>
#include <memory>
#include <cstring>
int main(int argc, const char *argv[]) {
std::unique_ptr<char[]> buff;
const char *s = "";
if (argc > 1) {
enum { BUFFER_SIZE = 32 };
try {
buff.reset(new char[BUFFER_SIZE]);
// ...
s = std::strncpy(buff.get(), argv[1], BUFFER_SIZE - 1);
} catch (std::bad_alloc &) {
// Handle error
}
}
std::cout << s << std::endl;
}
|
...
Code Block |
---|
|
#include <string>
std::string someStringReturningFunction();
void displayString(const char *);
void f() {
const char *str = someStringReturningFunction().c_str();
displayString(str); /* Undefined behavior */
} |
Compliant solution (std::string::c_str()
)
...
Search for other vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...