首页 > 解决方案 > 如何解决函数调用中的 gcc [-Werror=format-security]?

问题描述

我有这个对czmq api 的调用:

int rc = zsock_connect(updates, ("inproc://" + uuidStr).c_str());
(Note: uuidStr is of type std::string and zsock_connect expects a const char* as its second argument)

这给出了编译器错误:

error: format not a string literal and no format arguments [-Werror=format-security]
int rc = zsock_connect(updates, ("inproc://" + uuidStr).c_str());
                                                               ^                                                                                                    

我试过了:

const char* connectTo = ("inproc://" + uuidStr).c_str();
int rc = zsock_connect(updates, connectTo);

并且

int rc = zsock_connect(updates, (const char*)("inproc://" + 
uuidStr).c_str());

但错误仍然存​​在。

我该如何纠正?

语境; 我正在尝试使用 pip install 将此代码编译为 Linux 上的 Python 扩展。在 Windows 上,它使用 pip install 编译并运行得很好,大概是编译器更宽松。

标签: linuxgcczeromq

解决方案


这个功能就像printf()和朋友一样,对吧?如果是这样,您将遇到与存在相同的问题printf(some_var)- 如果您传递的字符串中包含格式序列,您会得到未定义的行为和坏事发生,因为您没有告诉函数的参数期待。解决方法是执行以下操作:

int rc = zsock_connnect(updates, "inproc://%s", uuidStr.c_str());

基本上,给它一个将你的字符串作为参数的格式。


推荐阅读