Skip to content

Commit 73bc74a

Browse files
committed
Avoid footgun.
Factor temporary std::string instance to separate variable as this prolongs its lifetime long enough for result of .c_str to survive. Otherwise printf could obtain pointer to already destructed string. For more information consult GotW #88 at [1]. [1] https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/
1 parent b2daa48 commit 73bc74a

1 file changed

Lines changed: 6 additions & 3 deletions

File tree

echo_server.cpp

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ void handle_request(const std::error_code& error, tcp::socket socket) {
2222
server.async_accept(io, &handle_request); // The Loop
2323

2424
if (error) {
25-
printf("Error while accepting: %s\n", error.message().c_str());
25+
const auto &msg = error.message();
26+
printf("Error while accepting: %s\n", msg.c_str());
2627
return;
2728
}
2829

@@ -33,14 +34,16 @@ void handle_request(const std::error_code& error, tcp::socket socket) {
3334
asio::async_read_until(request->socket, request->buffer, '\n',
3435
[request](const auto &error, size_t bytes_transferred) {
3536
if (error) {
36-
printf("Error while reading: %s\n", error.message().c_str());
37+
const auto &msg = error.message();
38+
printf("Error while reading: %s\n", msg.c_str());
3739
return;
3840
}
3941
printf("Received %zu bytes\n", bytes_transferred);
4042
asio::async_write(request->socket, request->buffer,
4143
[request](const auto &error, size_t bytes_transferred) {
4244
if (error) {
43-
printf("Error while writing: %s\n", error.message().c_str());
45+
const auto &msg = error.message();
46+
printf("Error while writing: %s\n", msg.c_str());
4447
return;
4548
}
4649
printf("Sent %zu bytes\n", bytes_transferred);

0 commit comments

Comments
 (0)