...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <iostream>
#include <memory>
#include <cstring>
int main(int argc, const char *argv[]) {
const char *s = "";
if (argc > 1) {
enum { BufferSize = 32 };
try {
std::unique_ptr<char[]> buff(new char[BufferSize]);
std::memset(buff.get(), 0, BufferSize);
// ...
s = std::strncpy(buff.get(), argv[1], BufferSize - 1);
} catch (std::bad_alloc &) {
// Handle error
}
}
std::cout << s << std::endl;
}
|
Note that this code does not create a non-null-terminate This code always creates a null-terminated byte string, despite its use of strncpy()
. This is , because it leaves the final char
in the buffer set to its default value, which is set to 0 by operator new
.
Compliant Solution (std::unique_ptr
)
...
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 { BufferSize = 32 };
try {
buff.reset(new char[BufferSize]);
std::memset(buff.get(), 0, BufferSize);
// ...
s = std::strncpy(buff.get(), argv[1], BufferSize - 1);
} catch (std::bad_alloc &) {
// Handle error
}
}
std::cout << s << std::endl;
}
|
...