L
lovecreatesbeauty
/*
How does free() know how many elements should be freed in a dynamic
array?
When it frees a single variable, the size information about amount of
byte of memory can be retrieved from the type of variable itself.
Now, suppose there is an array of more than one element need to be
freed, as free() doesn't accept a argument indicating the size, how can
free() be aware of the count of elements? As shown in line #20.
Thank you
lovecreatesbeauty
*/
1 typedef struct
2 {
3 char account_name[200];
4 double balance;
5 } account;
6
7 int main(void)
8 {
9 int ret = 0;
10 const int ARR_CNT = 200;
11 account *pacc;
12 account *pacc_arr;
13
14 /* to allocate single object */
15 pacc = malloc(sizeof(*pacc));
16 free(pacc); /* size info. retrieved via type of variable
pacc */
17
18 /* to allocate object array */
19 pacc_arr = malloc(ARR_CNT * sizeof(*pacc));
20 free(pacc_arr); /* how can free() be aware of `ARR_CNT' */
21 return ret;
22 }
~
~
How does free() know how many elements should be freed in a dynamic
array?
When it frees a single variable, the size information about amount of
byte of memory can be retrieved from the type of variable itself.
Now, suppose there is an array of more than one element need to be
freed, as free() doesn't accept a argument indicating the size, how can
free() be aware of the count of elements? As shown in line #20.
Thank you
lovecreatesbeauty
*/
1 typedef struct
2 {
3 char account_name[200];
4 double balance;
5 } account;
6
7 int main(void)
8 {
9 int ret = 0;
10 const int ARR_CNT = 200;
11 account *pacc;
12 account *pacc_arr;
13
14 /* to allocate single object */
15 pacc = malloc(sizeof(*pacc));
16 free(pacc); /* size info. retrieved via type of variable
pacc */
17
18 /* to allocate object array */
19 pacc_arr = malloc(ARR_CNT * sizeof(*pacc));
20 free(pacc_arr); /* how can free() be aware of `ARR_CNT' */
21 return ret;
22 }
~
~