Skip to content

Commit

Permalink
Use snprintf instead of sprintf
Browse files Browse the repository at this point in the history
- Augment the buffer size on doc error.
- Let sprintf in switch_node.h since the max. string length is known.

Signed-off-by: Gaël Écorchard <gael@km-robotics.cz>
  • Loading branch information
Gaël Écorchard committed Jan 17, 2024
1 parent 574a34f commit efcd29d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
13 changes: 5 additions & 8 deletions src/xml_parsing.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
Expand All @@ -23,10 +24,6 @@
#pragma GCC diagnostic ignored "-Wattributes"
#endif

#ifdef _MSC_VER
#pragma warning(disable : 4996) // do not complain about sprintf
#endif

#include <map>
#include "behaviortree_cpp/xml_parsing.h"
#include "tinyxml2/tinyxml2.h"
Expand Down Expand Up @@ -239,8 +236,8 @@ void XMLParser::PImpl::loadDocImpl(XMLDocument* doc, bool add_includes)
{
if (doc->Error())
{
char buffer[200];
sprintf(buffer, "Error parsing the XML: %s", doc->ErrorStr());
char buffer[512];
snprintf(buffer, sizeof buffer, "Error parsing the XML: %s", doc->ErrorStr());
throw RuntimeError(buffer);
}

Expand Down Expand Up @@ -350,14 +347,14 @@ void VerifyXML(const std::string& xml_text,
if (xml_error)
{
char buffer[512];
sprintf(buffer, "Error parsing the XML: %s", doc.ErrorName());
snprintf(buffer, sizeof buffer, "Error parsing the XML: %s", doc.ErrorName());
throw RuntimeError(buffer);
}

//-------- Helper functions (lambdas) -----------------
auto ThrowError = [&](int line_num, const std::string& text) {
char buffer[512];
sprintf(buffer, "Error at line %d: -> %s", line_num, text.c_str());
snprintf(buffer, sizeof buffer, "Error at line %d: -> %s", line_num, text.c_str());
throw RuntimeError(buffer);
};

Expand Down
4 changes: 3 additions & 1 deletion tests/test_helper.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#ifndef TEST_HELPER_HPP
#define TEST_HELPER_HPP

#include <cstdio>

#include "behaviortree_cpp/bt_factory.h"

inline BT::NodeStatus TestTick(int* tick_counter)
Expand All @@ -17,7 +19,7 @@ void RegisterTestTick(BT::BehaviorTreeFactory& factory, const std::string& name_
{
tick_counters[i] = false;
char str[100];
sprintf(str, "%s%c", name_prefix.c_str(), char('A'+i ) );
snprintf(str, sizeof str, "%s%c", name_prefix.c_str(), char('A'+i ) );
int* counter_ptr = &(tick_counters[i]);
factory.registerSimpleAction(str, std::bind(&TestTick, counter_ptr));
}
Expand Down

0 comments on commit efcd29d

Please sign in to comment.