c将带有指针的结构从堆栈复制到堆 [英] c copy struct with pointers from stack to heap

查看:47
本文介绍了c将带有指针的结构从堆栈复制到堆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下类型

typedef struct {
  const void *data;
  uint32_t offset[2];
} TSNode;

我有一个包含分配的函数:

I've got a function which contains an assignement:

TSNode* myFun() {
    TSNode node = get_node();
    // rest of code
}

由于这里将 node 分配到堆栈内存中,因此一旦函数结束,它将消失.我想稍后再跟踪该节点,所以我想将其复制到堆中.

Since node is allocated on stack memory here, it'll vanish once the function has ended. I want to keep track of that node at later points, so I thought to just copy it to the heap.

TSNode* myFun() {
    TSNode node = get_node();

    TSNode* heapNode = malloc(sizeof(TSNode));
    memcpy(heapNode, &node, sizeof(TSNode));
    return heapNode;
}

此memcpy是否将所有数据正确分配给分配给 heapNode 的堆?即在此过程中没有任何损坏& * data 是否完整?

Does this memcpy all data correctly to my heap allocated heapNode? i.e. nothing is corrupted in the process & the *data is intact?

推荐答案

此memcpy是否将所有数据正确发送到我分配给堆的heapNode?即在此过程中没有任何损坏&*数据是否完整?

Does this memcpy all data correctly to my heap allocated heapNode? i.e. nothing is corrupted in the process & the *data is intact?

这个问题的答案是, memcpy 使用 shallow copy 概念.在 shallow copy 中,原始结构(节点)中的指针 TSNode node = get_node(); 将被复制到新节点 heapNode ( TSNode * heapNode )一点一点地调用逐位复制.因此,新的 heapNode 指针也将指向与原始节点的指针( TSNode node = get_node(); )指针相同的位置,该指针是通过复制值的位置memcpy .因此,一旦控件从函数 myFun 返回,则原始节点将从内存中释放.因此,您的新节点指针将变为悬挂指针.这是 memcpy 的严重副作用.

The answer to this question is, memcpy use shallow copy concept. In shallow copy the pointer in your original structure (node) TSNode node = get_node(); will be copied to the new node heapNode (TSNode* heapNode) bit by bit also call bit wise copy. So your new heapNode pointers will also pointing to the same location as your original node's (TSNode node = get_node();) pointers from where you copied the value with memcpy. Hence once control returns from function myFun your original node will be released from memory. Therefore your new node pointers will become dangling pointers. That is a critical side effect of memcpy.

这篇关于c将带有指针的结构从堆栈复制到堆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆