...
| 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]);
// ...
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 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)
...