【问题标题】:Copy data to member of structure using memcpy given a double pointer to the structure给定结构的双指针,使用 memcpy 将数据复制到结构的成员
【发布时间】:2013-10-07 21:51:36
【问题描述】:

我想将数据复制到一个结构成员,给定一个指向该结构的双指针。 我无法更改copyFoo() 的签名。 成员 cnt 按预期被分配了GetCnt() 的返回值,但是当我这样使用memcpy 时会产生访问冲突。 当我有一个指向结构的双指针和一个 void 指针成员时,有人可以详细说明如何使用 memcpy 吗?非常感谢!

struct mystruct
{
    void * data;
    unsigned int cnt;

};

void copyFoo( myObj * inBar, mystruct **outFoo)
{
  memcpy((*outFoo)->data, inBar->GetData(), inBar->GetLength() );
  (*outFoo)->cnt=  inBar->GetCnt();
}

int main(void){

myObj *in = getObj();
mystruct *out= new mystruct;
copyFoo(in, &out));
delete in;
delete out;

}

inbar 的成员函数 GetData() 返回一个 void 指针,GetCnt() 返回 unsigned intGetLength() 返回一个 int

【问题讨论】:

  • 能否请您也显示调用copyFoo的代码?
  • 假设inBar 是一个有效地址,在调用该memcpy 之前,您是否费心将inBar->data 设置为足够大的内存缓冲区分配?如果不是,您正在调用未定义的行为

标签: c++ memcpy


【解决方案1】:

在尝试将数据复制到其中之前,应分配适当大小的内存块:

void copyFoo(myObj *inBar, mystruct **outFoo)
{
    (*outFoo)->data = malloc(inBar->GetLength());                     // <-- THIS
    memcpy((*outFoo)->data, inBar->GetData(), inBar->GetLength());
    (*outFoo)->cnt=  inBar->GetCnt();
}

如果mystructdata 成员尚未初始化或指向已被释放的内存,copyFoo 函数将调用未定义行为

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多