我正在编写C ++代码并尝试使用unsigned char*
将string
数组转换为stringstream
。
代码段:
unsigned char * arr;
do{
fill(*arr);
//if I print the array here, the print operation works fine
stringstream s((const char*)arr); //I also tired other castings without success
cout<<s.str()<<endl;
//condition...
} while(condition);
这是因为我必须重复它。问题是我在这里得到了一个Segmentation fault(core dumped)错误:stringstream s((const char*)arr);
这是一个更详细的代码。 fill
是libusb_interrupt_transfer
int len = 64;
int transferred;
unsigned char *pkt = new unsigned char[len];
unsigned char * arr;
int arrLen;
do {
libusb_interrupt_transfer(handle, (EP_IN | LIBUSB_ENDPOINT_IN), pkt, len, &transferred, 1000);
arrLen = pkt[6];
arr = new unsigned char[arrLen];
for (int i = 0; i < arrLen; i++) {
arr[i] = pkt[i+7];
}
stringstream s;
s << (char*) arr;
}
答案 0 :(得分:1)
我会选择:
stringstream s;
s << (char*) arr;
修改强>
好的,所以在你给我们Fill()
后,我认为这就是问题:
基于此链接:http://libusb.sourceforge.net/api-1.0/group__syncio.html#gac412bda21b7ecf57e4c76877d78e6486您可以从不假设您将在len
中传递字符数量。您应该使用transferred
来检查已转移的字符数。
直接问题出在你写的那一刻
arrLen = pkt[6];
因为pkt [6]很可能尚未初始化。在这种情况下,它包含一些随机数(如果我们假设该数字实际上是随机的)给你一个 1到2 ^ 31 - (64 - 7)访问冲突的概率 - 如果{{ 1}}太大了,你会很快超过arrLen
范围。
所以我会建议这样的事情:
pkt
此外,在错误发生时将libusb_interrupt_transfer(handle, (EP_IN | LIBUSB_ENDPOINT_IN), pkt, len, &transferred, 1000);
// AHTUNG! ATTENTION!
if (transferred >= 7) // and you'll need even more
continue;
arrLen = pkt[6];
arr = new unsigned char[arrLen];
for (int i = 0; i < arrLen; i++) {
arr[i] = pkt[i+7];
}
stringstream s;
s << (char*) arr;
和pkt
转储会很不错。这样可以更容易地分析问题。