c - Why does free work like this? -


given following code:

typedef struct tokens {     char **data;     size_t count; } tokens;  void freetokens(tokens *tokens) {     int d;     for(d = 0;d < tokens->count;d++)         free(tokens->data[d]);     free(tokens->data);     free(tokens);     tokens = null; } 

why need extra:

free(tokens->data); 

shouldn't handled in loop?

i've tested both against valgrind/drmemory , indeed top loop correctly deallocates dynamic memory, if remove identified line leak memory.

howcome?

let's @ diagram of memory you're using in program:

+---------+       +---------+---------+---------+-----+ | data    |  -->  | char *  | char *  | char *  | ... | +---------+       +---------+---------+---------+-----+ | count   |            |         |         | +---------+            v         v         v                      +---+     +---+     +---+                      | |     | b |     | c |                      +---+     +---+     +---+                      |...|     |...|     |...|                      +---+     +---+     +---+ 

in c, can dynamically allocate space group (more simply, array) of elements. however, can't use array type reference dynamic allocation, , instead use pointer type. in case, pointer points first element of dynamically allocated array. if add 1 pointer, you'll pointer second element of dynamically allocated array, add 2 pointer second element, , on.

in c, bracket syntax (data[1]) shorthand addition , dereferencing pointer. pointers in c can used arrays in way.

in diagram, data pointing first char * in dynamically allocated array, elsewhere in memory.

each member of array pointed data string, dynamically allocated (since elements char *s).

so, loop deallocates strings ('a...', 'b...', 'c...', etc), free(tokens->data) deallocates array data points to, , finally, free(tokens) frees entire struct.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -