c - Calloc does not initialize entire memory block to zero -


while playing implementation of hashmap toy example (for fun) i've found strange behaviour, calloc not initialize entire memory block want zero, supposed do. following code should produce no output if entire memory block zeroed:

#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h>  #define dict_initial_capacity 50   typedef struct dictionary_item {     char* ptr_key;     void* ptr_value; } dict_item;  typedef struct dictionary {     dict_item* items;     uint16_t size, max_capacity; } dict;  dict* dict_new() {     dict *my_dict = calloc(1, sizeof *my_dict);     my_dict->items = calloc(dict_initial_capacity, sizeof my_dict->items);     my_dict->size = 0;     my_dict->max_capacity = dict_initial_capacity;          (int j = 0; j < my_dict->max_capacity; j++) {         int key_null = 1;         int value_null = 1;         if ((my_dict->items + j)->ptr_key != null)             key_null = 0;         if ((my_dict->items + j)->ptr_value != null)             value_null = 0;         if ((my_dict->items + j)->ptr_key != null || (my_dict->items + j)->ptr_value != null)             printf("item %d, key_null %d, value_null %d\n", j, key_null, value_null);     }     return my_dict; }   int main(int argc, char** argv) {      dict* dict = dict_new();   } 

however produces output:

item 25, key_null 1, value_null 0 

the non-zero item 1 @ dict_initial_capacity / 2. i've tried using memset put block 0 , result same. if put memory 0 explicitly using:

for (int j = 0; j < my_dict->max_capacity; j++){             (my_dict->items + j)->ptr_key = 0;             (my_dict->items + j)->ptr_value = 0;         } 

then desired behavior. not understand why not work using calloc. doing wrong?

my_dict->items = calloc(dict_initial_capacity, sizeof my_dict->items); 

should be

my_dict->items = calloc(dict_initial_capacity, sizeof *my_dict->items); 

also note that, in general, calloc may not set pointers null (although on modern systems know of). safer explicitly initialize pointers meant null.

having said that, seem storing size variable indicate size of dictionary, avoid problem entirely not reading entries beyond current size; , when increase size initialize entries have added.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -