How does free() know how many elements should be freed in a dynamic array?

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 }
~
~
 
M

Mike Wahler

lovecreatesbeauty said:
/*

How does free() know how many elements should be freed in a dynamic
array?

Same answer as the last time you asked: Read The FAQ.

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top