Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Valgrind:条件跳转或移动取决于未初始化的值。检查为空。C_C_Memory Management_Valgrind - Fatal编程技术网

Valgrind:条件跳转或移动取决于未初始化的值。检查为空。C

Valgrind:条件跳转或移动取决于未初始化的值。检查为空。C,c,memory-management,valgrind,C,Memory Management,Valgrind,我有以下代码: // list.h typedef struct Node { struct Node *next; int *data; } Node; typedef struct List { Node *head; } List; // main.c #include <stdio.h> #include <stdlib.h> #include "helpers.h" int main() { // creating list Lis

我有以下代码:

// list.h

typedef struct Node {
  struct Node *next;
  int *data;
} Node;

typedef struct List {
  Node *head;
} List;

// main.c

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

int main()
{
  // creating list
  List *list = (List*)malloc(sizeof(List));
  Node *node = (Node*)malloc(sizeof(Node));
  list->head = node;

  // creating 5 empty nodes
  for (int i = 1; i < 5; i++)
  {
    node->next = (Node*)malloc(sizeof(Node));
    node = node->next;
  }

  // trying to fill it if it is empty
  node = list->head;

  for (int i = 1; i < 5; i++)
  {
    if (node->data == NULL)
    {
      node->data = (int*)malloc(sizeof(int));
      *(node->data) = 1;
    }
  }

  // freeing
  node = list->head;
  Node *tmp;
  while (node != NULL)
  {
    free(node->data);
    tmp = node;
    node = node->next;
    free(tmp);
  }

  free(list);
  return 0;
}
我不需要严格地在节点内部有一些东西,所以我的列表可以是这样的
[1,1,null,1,null]
。但是在代码中,我想使用if语句来检查
节点->数据是否已经存在(这是一个指针,所以我必须检查内存分配和数据是否指向某个值)


老实说,我的程序在某种程度上运行正常(它比我展示的示例代码更复杂,但valgrind错误类似),但我认为还是出了问题。

除了从不初始化任何
节点->数据
项外,您也不会为最后一个节点设置
节点->下一个
(节点->数据==NULL)
--节点->数据从未初始化。不需要强制执行malloc的返回,这是不必要的。请参阅:当您检查(节点->数据==NULL)--坏的jujuju时,它是一个未初始化的指针。。。分配列表节点时,始终初始化元素。例如,
Node*Node=malloc(sizeof*Node);if(!node){perror(“malloc node”);返回1;};节点->数据=NULL;节点->下一步=空。这样你就永远不会遇到这两个问题。(也考虑添加一个<代码>尾部<代码>指针到您的代码>列表 CALLUNE():不保证将指针初始化为<代码> null <代码>,只有整数类型。@ MeVets将数据设置为零表示,但这不一定是空指针的表示形式。
==340== Conditional jump or move depends on uninitialised value(s)
==340==    at 0x10870A: main (main1.c:24)