被释放后修改 - 在结构中返回 `c_str` (const char*) 的 C 数组

modified after being freed - returning a C array of `c_str` (const char*) within a struct

如何从 std::vector(在 struct 中)获取 c_str 数组供 C 用户使用?

尝试:

#include <vector>
#include <algorithm>

typedef struct { size_t size; const char** arr; } CStrStrArray;

CStrStrArray f() {
    const std::vector<const char*> cStrVec {"foo", "bar"}; 
    /* pretend ^this is huge^ with size + contents not known ahead of time */

    const char **cStrArr = (const char**)malloc(cStrVec.size());
    std::copy(cStrVec.begin(), cStrVec.end(), cStrArr);
    /* also tried `cStrVec.data();` */
    return {cStrVec.size(), cStrArr};
}

/* pretend this is 'main.c' and the above is in an `extern C` elsewhere */
int main(void) {
    CStrStrArray c_str_arr = f();
    free(c_str_arr.arr);
    c_str_arr.size = 0;
    return EXIT_SUCCESS;
}

错误:

malloc: Incorrect checksum for freed object 0x7ff996d3d790: probably modified after being freed.
Corrupt value: 0x7ff996d08280
executable(17572,0x11c6d5e00) malloc: *** set a breakpoint in malloc_error_break to debug

您的代码没有分配足够的内存。您只为 2 个字节分配内存,但您需要为 2 个字符指针分配内存。所以把它改成:

malloc(cStrVec.size()) --> malloc(cStrVec.size() * sizeof *cStrArr)
                                  \------------/   \--------------/
                                   Number of        size of a single
                                   char pointers    char pointer
                                   in the vector

                                  \-------------------------------/
                                          Memory needed

如果您需要将 std::vector<std::string>> 转换为 CStrStrArray,则不需要中间步骤并创建额外的 std::vector<const char *>:

CStrStrArray f( const std::vector<std::string> &v ) {
    CStrStrArray r{ v.size(), 
         reinterpret_cast<const char **>( malloc( sizeof( char * ) * v.size() ) };
    for( size_t i = 0; i < v.size(); ++i )
        r.arr[i] = strdup( v[i].c_str() );
    return r;
}