【发布时间】:2021-07-27 09:49:42
【问题描述】:
如何从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
【问题讨论】:
-
嗨@AT - 你不是在复制内容,你是在复制指针 - 当方法完成时内容范围完成..尝试将“foo”作为方法之外的静态常量和看看有什么不同。
-
@MrR 这是指向字符串文字的指针,所以可以复制指针
标签: c++ arrays c malloc c-strings