【问题标题】:Why does memory allocated my malloc get written over? [duplicate]为什么分配给我的 malloc 的内存会被覆盖? [复制]
【发布时间】:2020-09-25 16:26:04
【问题描述】:

下面的代码sn-p 在create() 函数中为一个Node 分配内存,并创建一个名为list 的指针指向该Node 的指针。然后它在 main() 中为另一个节点分配更多内存,最后在 test() 中为另一个节点分配内存。在 test() 中为节点分配内存后,存储在列表中的数据会更改。为什么会这样?

#include <stdio.h>
#include <stdlib.h>

typedef struct Node Node;

typedef struct Node {
    int data;
} Node;

Node **create(void)
{
    Node *head = malloc(sizeof(Node));
    head->data = 1;
    Node **list = &head;
    return list;
}

void test(void)
{
    Node *node = malloc(sizeof(Node));
}

int main()
{
    Node **list = create();
    printf("Data after create(): %d\n", (*list)->data);
    Node *node = malloc(sizeof(Node));
    printf("Data after allocating memory for new node in main(): %d\n", (*list)->data);
    test();
    printf("Data after allocating memory for new node in test(): %d\n", (*list)->data);

    return 0;
}

样本输出:

Data after create(): 1
Data after allocating memory for new node in main(): 1
Data after allocating memory for new node in test(): -129660600

【问题讨论】:

标签: c malloc


【解决方案1】:

您的代码过于复杂和错误,尤其是这个:

Node **list = &head;
return list;

将返回一个局部变量的地址,一旦函数终止,该变量将不再存在。

您可能只是想要这个(尽管该代码没有多大意义):

#include <stdio.h>
#include <stdlib.h>

typedef struct Node Node;

typedef struct Node {
  int data;
} Node;

Node* create(void)
{
  Node* head = malloc(sizeof(Node));
  head->data = 1;
  return head;
}

void test(void)
{
  Node* node = malloc(sizeof(Node));
}

int main()
{
  Node* list = create();
  printf("Data after create(): %d\n", list->data);
  Node* node = malloc(sizeof(Node));
  printf("Data after allocating memory for new node in main(): %d\n", list->data);
  test();
  printf("Data after allocating memory for new node in test(): %d\n", list->data);

  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-08
    • 2021-12-10
    • 2020-03-06
    • 2021-10-16
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2019-03-03
    相关资源
    最近更新 更多