c++ - 为什么将字符串分配给 const char * 然后将 const char * 作为缓冲区 (void*) 传递给函数时结果不正确?

标签 c++ string parameter-passing

(我正在使用库 libmicrohttpd )

像这样的 const char * 工作得很好:

const char *page = "Hello World";
MHD_create_response_from_buffer(strlen(page), (void*)page, MHD_RESPMEM_PERSISTENT);

但是给 const char * 赋值一个字符串会在客户端输出一个奇怪的字符串:

std::string str = "Hello World";
const char *page = str.c_str();
MHD_create_response_from_buffer(strlen(page), (void*)page, MHD_RESPMEM_PERSISTENT);

或:

std::string str = "Hello World";
MHD_create_response_from_buffer(strlen(page.c_str()), &page[0], MHD_RESPMEM_PERSISTENT);

第二个和第三个代码片段在客户端的输出是“♬♬♬♬gin”。不是“ Hello World ”。

为什么?

最佳答案

str 的生命周期在它被库使用之前就结束了。

在这种特定情况下,使 libmicrohttpd 复制缓冲区应该可以解决问题。

更具体地说,MHD_create_response_from_buffer的模式参数需要设置为 MHD_RESPMEM_MUST_COPY,因为您的源缓冲区(字符串内部)的生命周期比函数返回的 MHD_Response 短。

关于c++ - 为什么将字符串分配给 const char * 然后将 const char * 作为缓冲区 (void*) 传递给函数时结果不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55991856/

相关文章:

c++ - 如何将 std::vector<myClass*> 转换为 std::vector<const myClass* const>?

c++ - 如何检查指令是否为 LLVM IR 中的 PHI 指令

r - R提取字符串的一部分

C 中函数结构错误的类型冲突

ruby-on-rails - Rails 表单在验证错误后呈现错误的 URL(不保留传递的参数)

c++ - <iosfwd> header 是什么?

c++ - realloc 内存在 C++ 中无法正常工作

string - 检查Tcl中字符串是否包含片段

python - 如何在 Python 字符串模板类上转义 $?

java - 在 Java 类 Android 应用程序之间传递字符串数组