Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8737c14

Browse files
authored
Update WrongInDetectingAndHandlingMemoryAllocationErrors.cpp
1 parent 20e19ec commit 8737c14

1 file changed

Lines changed: 26 additions & 27 deletions

File tree

Lines changed: 26 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,31 @@
1-
// BAD: no memory allocation errors are detected
2-
void f(const int *array, std::size_t size) noexcept {
3-
int *copy = new int[size];
4-
std::memcpy(copy, array, size * sizeof(*copy));
5-
// ...
6-
delete [] copy;
1+
// BAD: on memory allocation error, the program terminates.
2+
void badFunction(const int *source, std::size_t length) noexcept {
3+
int * dest = new int[length];
4+
std::memset(dest, 0, length);
5+
// ..
76
}
8-
// GOOD: memory allocation errors are detected
9-
void f(const int *array, std::size_t size) noexcept {
10-
int *copy;
7+
// GOOD: memory allocation error will be handled.
8+
void goodFunction(const int *source, std::size_t length) noexcept {
119
try {
12-
copy = new int[size];
13-
} catch(std::bad_alloc) {
14-
// Handle error
15-
return;
16-
}
17-
// At this point, copy has been initialized to allocated memory
18-
std::memcpy(copy, array, size * sizeof(*copy));
19-
// ...
20-
delete [] copy;
10+
int * dest = new int[length];
11+
} catch(std::bad_alloc)
12+
std::memset(dest, 0, length);
13+
// ..
14+
}
15+
// BAD: memory allocation error will not be handled.
16+
void badFunction(const int *source, std::size_t length) noexcept {
17+
try {
18+
int * dest = new (std::nothrow) int[length];
19+
} catch(std::bad_alloc)
20+
std::memset(dest, 0, length);
21+
// ..
2122
}
22-
// GOOD: memory allocation errors are detected
23-
void f(const int *array, std::size_t size) noexcept {
24-
int *copy = new (std::nothrow) int[size];
25-
if (!copy) {
26-
// Handle error
27-
return;
23+
// GOOD: memory allocation error will be handled.
24+
void goodFunction(const int *source, std::size_t length) noexcept {
25+
int * dest = new (std::nothrow) int[length];
26+
if (!dest) {
27+
return;
2828
}
29-
std::memcpy(copy, array, size * sizeof(*copy));
30-
// ...
31-
delete [] copy;
29+
std::memset(dest, 0, length);
30+
// ..
3231
}

0 commit comments

Comments
 (0)