代码之家  ›  专栏  ›  技术社区  ›  A T

释放后修改-在结构中返回“C_str”(const char*)的C数组

  •  0
  • A T  · 技术社区  · 3 年前

    如何从 std::vector struct )供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
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   4386427    3 年前

    你的代码没有分配足够的内存。只为2个字节分配内存,但需要为2个字符指针分配内存。所以改变一下:

    malloc(cStrVec.size()) --> malloc(cStrVec.size() * sizeof *cStrArr)
                                      \------------/   \--------------/
                                       Number of        size of a single
                                       char pointers    char pointer
                                       in the vector
    
        2
  •  0
  •   Slava    3 年前

    如果你需要转换 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;
    }