getting the size of allocated space

This is a discussion on getting the size of allocated space within the C Programming forums, part of the General Programming Boards category; Given the following code: Code: int *p = malloc(sizeof(int) * 20); If I had no idea how much space was ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    69

    getting the size of allocated space

    Given the following code:

    Code:
    int *p = malloc(sizeof(int) * 20);
    If I had no idea how much space was allocated, how would I get the size of the space that the pointer p is pointing to (which would be 80 in this case)?

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,622
    Use real variables for size instead of magic numbers.

  3. #3
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    It's platform specific (see MSDN for windows, I don't know how to do it on linux). I suggest you keep track if it yourself though.

    For example:
    Code:
    size_t pSize = 0;
    int * p = NULL;
    
    pSize = 20 * sizeof(int);
    p = malloc(pSize);

  4. #4
    Registered User
    Join Date
    Jan 2008
    Posts
    58
    If I had no idea how much space was allocated
    How is that possible? You know how much space was allocated because you know what you passed to malloc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. Size of allocated memory
    By TriKri in forum C++ Programming
    Replies: 8
    Last Post: 11-27-2006, 12:22 PM
  3. char problem
    By eXistenZ in forum Windows Programming
    Replies: 36
    Last Post: 02-21-2005, 05:32 AM
  4. someone who is good at finding and fixing bugs?
    By elfjuice in forum C++ Programming
    Replies: 8
    Last Post: 06-07-2002, 03:59 PM
  5. total size of dynamic memory allocated array
    By trekker in forum C Programming
    Replies: 10
    Last Post: 03-10-2002, 11:59 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21