c - Difficulties with understanding reallocating using malloc -
i trying increase size of collection
structure using malloc
instead of realloc
. i'm afraid i've made mistakes while assigning variables because i'm getting:
malloc: *** error object 0x7fd46b404ac8: pointer being freed not allocated
i appreciate if give me helpful hint.
void increasecollectionsize(){ collection.size = (collection.size + 1) * reallocate_modifier; char **increasedcollection = malloc(sizeof(char *) * collection.size); char **increasedhead = increasedcollection; for(int = 0; < collection.numberofwords; i++){ *increasedcollection = *collection.words; increasedcollection++; collection.words++; } free(collection.words); // i'm getting error here. collection.words = increasedhead; } typedef struct collection{ char **words; size_t numberofwords; size_t size; } collection;
cheers!
you free final value of collection.words
, pointer end of original memory block (due ++ in loop).
void increasecollectionsize(){ collection.size = (collection.size + 1) * reallocate_modifier; char **increasedcollection = malloc(sizeof(char *) * collection.size); char **increasedhead = increasedcollection; char **originalwords = collection.words; // save pointer for(int = 0; < collection.numberofwords; i++){ *increasedcollection = *collection.words; increasedcollection++; collection.words++; } free(originalwords); // ok collection.words = increasedhead; }
or, reducing complexity:
void increasecollectionsize() { collection.size = (collection.size + 1) * reallocate_modifier; char **increasedcollection = malloc(sizeof(char *) * collection.size); assert(increasedcollection != null); // explicitly abort() on malloc() error (size_t = 0; < collection.numberofwords; i++) increasedcollection[i] = collection.words[i]; free(collection.words); collection.words = increasedcollection; }
Comments
Post a Comment