简体   繁体   English

C:Valgring警告“大小为8的无效写入/读取”并关闭syscall

[英]C : Valgring warns about “Invalid write/read of size 8” & close syscall

I'm testing my binary with valgrind, and I get many warnings like this one : 我正在用valgrind测试我的二进制文件,并且收到许多这样的警告:

Invalid write of size 8
==7414==    at 0x402AAE: list_create_node (simple_list.c:53)
==7414==    by 0x40267E: list_add_elem_at_back (simple_list2.c:21)
==7414==    by 0x401C8A: parse (is_valid2.c:31)
==7414==    by 0x40246C: ko_parse (main.c:53)
==7414==    by 0x40255B: ko (main.c:74)
==7414==    by 0x4025E1: main (main.c:96)
==7414==  Address 0x6fe52d8 is 0 bytes after a block of size 8 alloc'd
==7414==    at 0x4C277AB: malloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==7414==    by 0x402A75: list_create_node (simple_list.c:50)
==7414==    by 0x40267E: list_add_elem_at_back (simple_list2.c:21)
==7414==    by 0x401C8A: parse (is_valid2.c:31)
==7414==    by 0x40246C: ko_parse (main.c:53)
==7414==    by 0x40255B: ko (main.c:74)
==7414==    by 0x4025E1: main (main.c:96)

I saw that there are many posts about that but I can't find where's the problem in my code : 我看到有很多关于此的文章,但是我找不到我的代码中的问题所在:

t_node          *list_create_node(char *element)
{
  t_node        *node;

  if ((node = malloc(sizeof(t_node *))) == NULL)
    return (NULL);
  if ((node->value = strdup(element)))
    node->next = NULL; //// line 53 from simple_list.c
  return (node);
}

Am I doing something wrong? 难道我做错了什么?

Valgrind also warns about reading...And that : Valgrind还警告阅读...并且:

==7415== Warning: invalid file descriptor 1024 in syscall close()

I have a close() smewhere in my code, but even when I comment it, the message keeps being displayed. 我的代码中有一个close()位置,但是即使在我对其进行注释时,该消息仍会一直显示。 Why is that? 这是为什么?

You'll want to malloc the size of what your pointer is pointing to, not the size of the pointer itself. 你要malloc你的指针指向,而不是指针本身的大小尺寸。 Ie: change 即:更改

(node = malloc(sizeof(t_node *)))

to

(node = malloc(sizeof(t_node)))

or better yet: 或更好:

(node = malloc(sizeof *node))

Then you don't have to change the malloc -call if you decide to change the type of node . 然后,如果您决定更改node的类型,则不必更改malloc -call。

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

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