ivanmejiarocha / micro-service

sample micro-service in C++
MIT License
263 stars 129 forks source link

snprintf possible truncation #32

Open AdhamSorour opened 1 year ago

AdhamSorour commented 1 year ago

Got the following error when making:

.../micro-service/libs/cpprestsdk/Release/src/http/common/http_helpers.cpp: In function ‘size_t web::http::details::chunked_encoding::add_chunked_delimiters(uint8_t*, size_t, size_t)’:
.../micro-service/libs/cpprestsdk/Release/src/http/common/http_helpers.cpp:91:43: error: ‘%8zX’ directive output may be truncated writing between 8 and 16 bytes into a region of size 9 [-Werror=format-truncation=]
   91 |         snprintf(buffer, sizeof(buffer), "%8zX", bytes_read);
      |                                           ^~~~
.../micro-service/libs/cpprestsdk/Release/src/http/common/http_helpers.cpp:91:42: note: directive argument in the range [1, 18446744073709551615]
   91 |         snprintf(buffer, sizeof(buffer), "%8zX", bytes_read);
      |                                          ^~~~~~
.../micro-service/libs/cpprestsdk/Release/src/http/common/http_helpers.cpp:91:17: note: ‘snprintf’ output between 9 and 17 bytes into a destination of size 9
   91 |         snprintf(buffer, sizeof(buffer), "%8zX", bytes_read);
      |         ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1plus: all warnings being treated as errors
make[2]: *** [src/CMakeFiles/cpprest.dir/build.make:121: src/CMakeFiles/cpprest.dir/http/common/http_helpers.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:113: src/CMakeFiles/cpprest.dir/all] Error 2
make: *** [Makefile:160: all] Error 2

Solved by checking the return value of snprintf in micro-service/libs/cpprestsdk/Release/src/http/common/http_helpers.cpp:89/91:

#ifdef _WIN32
    int ret = sprintf_s(buffer, sizeof(buffer), "%8IX", bytes_read);
    if (ret < 0) abort();
#else
    int ret = snprintf(buffer, sizeof(buffer), "%8zX", bytes_read);
    if (ret < 0) abort();
#endif

I suppose you could also disable warnings being treated as errors