使用 Valgrind 对 calloc 进行无效写入

Cra*_*der 1 c valgrind

在这个创建列表对象的小函数上

typedef struct list {
  list_item* head;
  list_item* tail;
  int count;
  pthread_mutex_t* mutex; 
} list;

list* createList(){
  list* list = calloc(1, sizeof(list));
  list->mutex = calloc(1, sizeof(pthread_mutex_t));
  pthread_mutex_init(list->mutex, NULL);
  return list;
}
Run Code Online (Sandbox Code Playgroud)

当我运行 valgrind 时,我有这个输出

==8362== Invalid write of size 4
==8362==    at 0x11A30: createList (linkedlist.c:8)
==8362==    by 0x11203: create_new_game (engine.c:82)
==8362==    by 0x10817: createGame (check_engine.c:29)
==8362==    by 0x10F43: test_cropping (check_engine.c:146)
==8362==    by 0x10F6F: main (check_engine.c:152)
==8362==  Address 0x4a65514 is 8 bytes after a block of size 4 alloc'd
==8362==    at 0x484A260: calloc (vg_replace_malloc.c:752)
==8362==    by 0x11A0F: createList (linkedlist.c:7)
==8362==    by 0x11203: create_new_game (engine.c:82)
==8362==    by 0x10817: createGame (check_engine.c:29)
==8362==    by 0x10F43: test_cropping (check_engine.c:146)
==8362==    by 0x10F6F: main (check_engine.c:152)
Run Code Online (Sandbox Code Playgroud)

我不知道出了什么问题。它在我的 rapsberry pi 4 上运行。我做错了什么?

重命名修复了这个错误。现在它仍然是一个:

==8932== 24 bytes in 1 blocks are definitely lost in loss record 1 of 1
==8932==    at 0x484A260: calloc (vg_replace_malloc.c:752)
==8932==    by 0x11A23: createList (linkedlist.c:8)
==8932==    by 0x11203: create_new_game (engine.c:82)
==8932==    by 0x10817: createGame (check_engine.c:29)
==8932==    by 0x10F43: test_cropping (check_engine.c:146)
==8932==    by 0x10F6F: main (check_engine.c:152)
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 6

在这一行:

list* list = calloc(1, sizeof(list));
Run Code Online (Sandbox Code Playgroud)

您有一个名为 的类型list 一个名为 的变量list。因此,在sizeof(list)计算时,变量名称掩盖了类型名称,并且给出了变量(这是一个指针)的大小而不是类型的大小,因此您没有分配足够的内存。

为变量使用不同的名称:

list* createList(){
  list* listptr = calloc(1, sizeof(list));
  listptr->mutex = calloc(1, sizeof(pthread_mutex_t));
  pthread_mutex_init(listptr->mutex, NULL);
  listptr list;
}
Run Code Online (Sandbox Code Playgroud)