我正在编写一个C ++程序(见下文)。我的目标是将数据存储在iov struct中。我在构造函数中分配了固定长度的缓冲区。每次缓冲区被填满时,我都希望在iov中传输数据并分配固定长度的新缓冲区。最后,完成数据处理后,我想返回iov struct。我的目的是将所有这些数据存储到iov中,以便将来将来需要时可以轻松发送数据。我已经编写了示例代码。但是似乎没有用。我收到“公共汽车错误:10”。有人能帮我吗?
样例代码:
#include <iostream>
#include <string>
#include <sys/uio.h>
#include <cstdlib>
using namespace std;
#define MAX_LEN 1000
#define MIN_LEN 20
class MyClass
{
public:
MyClass();
~MyClass();
void fillData(std::string &data);
private:
struct iovec *iov;
unsigned int count;
unsigned int len;
char *buf;
unsigned int total_len;
unsigned int tmp_len;
};
MyClass::MyClass()
{
cout << "Inside constructor" << endl;
total_len = MIN_LEN;
buf = (char *)malloc(MAX_LEN);
if (buf == NULL) {
cout << "Error: can’t allocate buf" << endl;
exit(EXIT_FAILURE);
}
}
MyClass::~MyClass()
{
free(buf);
}
void MyClass::fillData(std::string &data)
{
unsigned int d_len, tmp_len, offset;
d_len = data.size();
const char* t = data.c_str();
total_len += d_len;
tmp_len += d_len;
if (total_len > MAX_LEN) {
/* Allocate memory and assign to iov */
tmp_len = d_len;
}
memcpy(buf + offset, t, d_len);
/* Adjust offset */
}
int main()
{
MyClass my_obj;
int i;
std::string str = "Hey, welcome to my first class!";
for (i = 0; i < 10; i++) {
my_obj.fillData(str);
}
return 0;
}
最佳答案
在没有详细了解程序意图的情况下,很明显,您忘记为iov
对象本身保留内存。
例如,在构造函数中,您编写iov[0].iov_base = buf
,但iov
之前尚未分配。
为了克服这个问题,在您第一次访问iov
的代码中,应该使用iov = calloc(100,sizeof(struct iovev))
编写类似new[]
或c ++的代码。
考虑以下程序:
struct myStruct {
char *buf;
int len;
};
int main() {
struct myStruct *myStructPtr;
myStructPtr->buf = "Herbert"; // Illegal, since myStructPtr is not initialized; So even if "Herbert" is valid, there is no place to store the pointer to literal "Herbert".
myStructPtr[0].buf = "Herbert"; // Illegal, since myStructPtr is not initialized
// but:
struct myStruct *myStructObj = new (struct myStruct);
myStructObj->buf = "Herbert"; // OK, because myStructObj can store the pointer to literal "Herbert"
myStructObj->buf = "Something else"; // OK; myStructObj can hold a pointer, so just let it point to a different portion of memory. No need for an extra "new (struct myStruct)" here
}