【问题标题】:copying a struct in a function and returning the copy in c在函数中复制结构并在 c 中返回副本
【发布时间】:2018-07-27 13:29:07
【问题描述】:

我正在使用 C 中的通用链表实现一个队列,其中列表中的每个节点都是一个简单的结构,其中包含一个 void 指针和一个指向下一个节点的节点指针。在出队操作中,我想删除头(工作正常),但我也想在删除后返回该节点。

编辑澄清

我在 dequeue 函数中所做的是(示例):

//This is my queue struct
typedef struct Queue{
    LinkedList* list;
    size_t item_size;
} Queue;

//this is the dequeue function
Node* dequeue(Queue* queue){
    Node* head = queue->list->head;
    Node* returnedValue = (Node*)malloc(sizeof(Node));
    memcpy(returnedValue, head, sizeof(Node));

    removeBegin(queue->list);
    return returnedValue;  
}

//this is the remove head function
void removeBegin(LinkedList* list){
    Node* tempHead = list->head;

    list->head = list->head->next;
    tempHead->next = NULL;
    free(tempHead->value);
    tempHead->value = NULL;
    free(tempHead);
    tempHead = NULL;
}

问题是在 free 功能正常之前的一切。一切都被正确复制。但是在 free 函数调用之后,复制到新分配节点的值立即变成垃圾(或 0)。

我调用函数的方式就是使用这个函数初始化队列:

Queue* init_queue(size_t size){
    Queue* queue = (Queue*)malloc(sizeof(Queue));
    // int x = 10;
    queue->list = createList(NULL, size);

    return queue;
}

然后调用 dequeue 并将队列的指针传递给它。

我该如何解决这个问题? 非常感谢。

【问题讨论】:

  • 请说明您是如何调用copyValue的,问题很可能出在那里。阅读:minimal reproducible example.
  • 哦,现在(我想)我明白了。当然,复制的值变得无效,因为您释放了它。仍然显示minimal reproducible example
  • 函数名有点用词不当——它实现了一个复制和释放(或移动)而不是复制
  • 不清楚你为什么要这样做。与其复制节点,您肯定只需要它包含的值吗?
  • 您在 memcpy() 调用中使用 n1->value 作为目标指针,而没有将其设置为任何内容。尝试改用calloc(),您更有可能得到段违规,从而告诉您真正的问题出在哪里。

标签: c memory struct memcpy


【解决方案1】:

内存分配使用

 Node* n1 = (Node*)malloc(sizeof(Node));

未初始化。这意味着访问 n1->value 的值会产生未定义的行为。结果是

memcpy(n1->value, n->value, sizeof(n->value));

还会给出未定义的行为。

当行为未定义时,执行任何进一步的代码的后果可能是任何事情。你的观察

新分配的节点变成垃圾(或0)

是一种可能的结果。

还有更多的问题。但是,您没有提供足够的信息(例如,函数是如何调用的?指针是如何作为n 初始化的?n->value 是如何初始化的?)因此无法就如何修复您的函数提供建议.

【讨论】:

  • 我为缺乏明确性表示歉意。我已经编辑了这个问题,以便清楚。我对 C 比较陌生。在我知道的大多数语言(例如 java)中,当你出队时,你删除值并返回它,这就是我想要做的。
猜你喜欢
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多