简体   繁体   中英

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 :

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 :

==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. Why is that?

You'll want to malloc the size of what your pointer is pointing to, not the size of the pointer itself. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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