Thread: Determining the sizeof dynamically allocated memory in C programming

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    10

    Determining the sizeof dynamically allocated memory in C programming

    Hi,

    Could any one please help me in determining the size of the dynamically allocated memory.


    #include <stdio.h>
    #include <malloc.h>

    int main()
    {
    int *mem;

    mem = (int*)malloc(5*sizeof(int));
    }

    here i need the no.of bytes allocated for the "mem" which is 20 bytes (assuming int is of 4 bytes). i believe this would be a very simple one but am new to this c programming and hence expecting help from you.

    Thanks in advance

    Regards,
    Anand V

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Just use a variable.

    size_t memsize = 5;
    int *mem = NULL;
    mem = malloc (sizeof mem[0] * memsize);

  3. #3
    Registered User
    Join Date
    Jul 2010
    Posts
    10
    Thanks for the prompt response.

    I need to keep track of the variable everytime when i allocate memory. so is there any way to identify the size of the allocated memory block using the pointer *mem?

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by anandvn View Post
    I need to keep track of the variable everytime when i allocate memory. so is there any way to identify the size of the allocated memory block using the pointer *mem?
    No, there is not.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    << !! Posting Code? Read this First !! >>
    If you're going to use C, you need to keep track of the size. Higher-level languages such as C++ allows you to escape this need, however.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Elysia View Post
    If you're going to use C, you need to keep track of the size. Higher-level languages such as C++ allows you to escape this need, however.
    C++ also does not provide any means to extract an allocated length if all you have is a pointer.

    The C++ library types (eg string, vector) keep track of the length of their contents, so it is possible (say) to determine how many elements are currently in a vector. As noted in previous posts, if you want to achieve that in C, you need to "roll your own" (i.e. keep track of the length yourself).
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  7. #7
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by grumpy View Post
    C++ also does not provide any means to extract an allocated length if all you have is a pointer.

    The C++ library types (eg string, vector) keep track of the length of their contents, so it is possible (say) to determine how many elements are currently in a vector. As noted in previous posts, if you want to achieve that in C, you need to "roll your own" (i.e. keep track of the length yourself).
    And maybe all of this is for the better. IMO not caring about remembering how much memory you allocate is kind of like not caring about the speed you are driving at.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by grumpy View Post
    C++ also does not provide any means to extract an allocated length if all you have is a pointer.
    I did say "escape", not a magical solution. Yes, if you have a pointer, then you don't know the size. But with templates, the compiler can help you remember the size (you can pass arrays be real reference in C++ actually, letting the compiler help you remember the size).
    And the standard library does remember its size. And then there's the standard arrays types std::vector and std::array which also keeps track of their size.

    Unfortunately, no such thing i n C.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Elysia View Post
    I did say "escape", not a magical solution.
    I realised what you meant. However, not everyone would read your words with sufficient precision to avoid misunderstanding or misinterpretation.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Very well, then. Now that's we've elaborated on the matter, perhaps it's point will get across better
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Fortunately, it's not so difficult to do in C.
    Just write a wrapper over malloc/calloc/realloc/free.
    EDIT:
    2nd EDIT: apology that i forgot to return p->data instead of p!
    The code is not tested. Use @ your own risk.
    Code:
    struct mem {
       void *data;
       size_t nbytes;
    } ;
    typedef struct mem mem;
    void *my_malloc(size_t n)
    {
       mem *p;
       p = malloc( sizeof(*p) + n );
       if(p == NULL) return NULL;
       p->nbytes = n;
       p->data     =   p + 1;        // tricky!
       return p->data;
    }
    void my_free(void *memp)
    {
        mem *p = memp;
        if(p == NULL) return ;        // behave just like free()
        p--;                                    // tricky!
        free(p);
    }
    size_t GetSize(void *memp)
    {
        mem *p = memp;
        p--;                                 
        return p->nbytes;
    }
    int main(void)
    {
         char *str = my_malloc( 100 );
         double *vec = my_malloc( 10 * sizeof(*vec) );
         // error check omitted
         printf("str bytes = %lu\n", GetSize(str) );
        my_free(str);
        my_free(vec);
        return 0;
    }
    Of course, you might want to abstract the implementation.
    Last edited by Bayint Naung; 07-25-2010 at 04:28 PM. Reason: modify code..

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    It seems a little pointless to allocate the structure itself. You are increasing the memory need by a lot. It would probably be better to copy the small struct instead. Or pass in a pointer to the struct that you can modify.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    >> You are increasing the memory need by a lot.
    hum? I don't get it?

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Actually nevermind. Did I read the code wrong last time or did you change it?
    Although, you are using mem and not struct mem and you're not typedefing the struct. Bug?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Memory allocated(no: of bytes) is the same as previous code.
    Where's the typedef line?
    Even if i forgot, i won't call it 'Bug'.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to retain an allocated memory
    By creek23 in forum C Programming
    Replies: 19
    Last Post: 06-24-2010, 10:19 PM
  2. problem with data in allocated memory
    By supi in forum C Programming
    Replies: 3
    Last Post: 06-09-2008, 02:06 AM
  3. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  4. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  5. scope of dynamically allocated variables
    By lanzyzhang in forum C Programming
    Replies: 4
    Last Post: 07-20-2004, 10:59 AM