dynamic - Make Realloc behave like Calloc -
how can force realloc behave calloc? instance:
i have following structs:
typedef struct bucket0{ int hashid; registry registry; }bucket; typedef struct table0{ int tsize; int telements; bucket** content; }table; and have following code in order grow table:
int grow(table* table){ bucket** tempptr; //grow add 1 number available buckets, , double it. table->tsize++; //add 1 table->tsize *= 2; //double element if(!table->content){ //table generated first time table->content = (bucket**)(calloc(sizeof(bucket*), table->tsize)); } else { //realloc content tempptr = (bucket**)realloc(table->content, sizeof(bucket)*table->tsize); if(tempptr){ table->content = tempptr; return 0; }else{ return 1000;//table not grow } } } when execute it, table grows properly, , of "buckets" in initialized null ptr. however, not of them are.
how can make realloc behave calloc? in sense when creates new "buckets" initialize null
strictly speaking, shouldn't relying on calloc (or memset, matter) set pointers null. c doesn't guarantee null pointers represented all-zero bytes in memory.
quoting comp.lang.c faq question 7.31:
don't rely on
calloc's 0 fill (see below); usually, it's best initialize data structures yourself, on field-by-field basis, if there pointer fields.
calloc's 0 fill all-bits-zero, , therefore guaranteed yield value 0 integral types (including'\0'character types). not guarantee useful null pointer values (see section 5 of list) or floating-point 0 values.
it's safer initialize individual structure fields yourself. can create static const 1 template, content initialized null, , memcpy each element of dynamically-allocated array.
Comments
Post a Comment