CrazyCoder
CrazyCoder

Reputation: 71

Invalid write with Valgrind on a calloc

On this small function that is creating a list object

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;
}

When I run valgrind I have this output

==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)

I don't find what is going wrong. It is running on my rapsberry pi 4. What am I doing wrong?

The renaming fixed this error. Now it remains one :

==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)

Upvotes: 1

Views: 126

Answers (1)

dbush
dbush

Reputation: 223689

On this line:

list* list = calloc(1, sizeof(list));

You have a type named list and a variable named list. So when sizeof(list) is calculated, the variable name masks the type name and the size of the variable (which is a pointer) is given instead of the size of the type, so you didn't allocate enough memory.

Use a different name for the variable:

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

Upvotes: 6

Related Questions