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

Discussion in 'C Programming' started by lovecreatesbeauty, Jan 13, 2006.

  1. /*

    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 }
    ~
    ~
    lovecreatesbeauty, Jan 13, 2006
    #1
    1. Advertising

  2. lovecreatesbeauty

    Mike Wahler Guest

    Re: [FAQ] How does free() know how many elements should be freed in a dynamic array?

    "lovecreatesbeauty" <> wrote in message
    news:...
    > /*
    >
    > 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
    Mike Wahler, Jan 13, 2006
    #2
    1. Advertising

  3. Mike Wahler wrote:
    > "lovecreatesbeauty" <> wrote in message
    > news:...
    > > /*
    > >
    > > 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


    very sorry, it's my fault.
    lovecreatesbeauty, Jan 13, 2006
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Abby
    Replies:
    2
    Views:
    600
  2. ravi
    Replies:
    72
    Views:
    1,454
    RCollins
    Sep 14, 2004
  3. apoorv

    How OS tackles mem. freed by free method

    apoorv, Feb 23, 2005, in forum: C Programming
    Replies:
    3
    Views:
    316
    Richard Bos
    Feb 23, 2005
  4. lovecreatesbeauty
    Replies:
    13
    Views:
    579
    Joe Wright
    Jan 15, 2006
  5. Andries

    I know, I know, I don't know

    Andries, Apr 23, 2004, in forum: Perl Misc
    Replies:
    3
    Views:
    221
    Gregory Toomey
    Apr 23, 2004
Loading...

Share This Page