简体   繁体   English

指针-访问内存位置不一致

[英]pointers - inconsistent access to memory location

I am trying to define a simple linked list 我正在尝试定义一个简单的链表

#include <stdio.h>


struct node{
  int value;
  struct node* next;
};


typedef struct {
  struct node* root;
} ll;

void add_to_ll(int value, ll* linked_list) {
  struct node new_node = {value, linked_list->root};
  linked_list->root = &new_node;
}

void print_ll(ll* ll2) {
  printf("%p", ll2);
  struct node* temp = ll2->root;
  while (temp->next != NULL) {
    printf("%d ", temp->value);
    temp = temp->next;
  }
}


int main()
{
  printf("Creating a linked list...\n");
  struct node root_node = {1, NULL};
  ll my_linked_list = { &root_node };
  for (int i = 0; i < 10000; i++) {
    add_to_ll(i, &my_linked_list);
  }
  printf("my_linked_list root value %d\n", my_linked_list.root->value);
  printf("my_linked_list root value %d\n", my_linked_list.root->value);
  printf("my_linked_list root value %d\n", my_linked_list.root->value);
  return 0;
}

The output I am getting is: 我得到的输出是:

Creating a linked list...
my_linked_list root value 9999
my_linked_list root value 429391991
my_linked_list root value 429391991

I am able to get the value of the root node correctly the first time. 我能够在第一时间正确获得rootvalue But on trying to read it the second time (and thereafter) the value changes. 但是在尝试第二次(及其后)读取时,该值会更改。 What am I missing? 我想念什么?

Your problem is with the memory allocation strategy in add. 您的问题与添加中的内存分配策略有关。

void add_to_ll(int value, ll* linked_list) {
  struct node new_node = {value, linked_list->root};
  linked_list->root = &new_node;
}

Here you're instatiating new_node as a local variable. 在这里,您将new_node设置为局部变量。 Non-static local variables have a lifespan equal to that of their block. 非静态局部变量的寿命等于其块的寿命。 After you exit the block, that memory (which is actually the stack) is available for successive allocations that will overwrite your object. 退出该块后,该内存(实际上是堆栈)可用于将覆盖对象的连续分配。 Use explicit allocation, that means malloc , to have objects whose lifespan is independent from the scope of allocation. 使用显式分配,即malloc ,使对象的寿命独立于分配范围。

I would also point out the naming... The most explicit name should be that of the type, not the variable. 我还要指出命名...最明确的名称应该是类型的名称,而不是变量。 So struct linked_list ll and not the other way around. 所以struct linked_list ll而不是相反。

This function: 该功能:

void add_to_ll(int value, ll* linked_list) {
  struct node new_node = {value, linked_list->root};
  linked_list->root = &new_node;
}

Constructs a node on the stack and adds it to the list. 在堆栈上构造一个节点并将其添加到列表中。 When you return from this function the stack is popped and the list root points to unallocated memory on the stack that will later be reused. 从此函数返回时,将弹出堆栈,并且列表根指向堆栈上未分配的内存,以后将重用该内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM