0

Is there a way to know from a pointer the size with which malloc() was called?

For example, if I have:

typedef struct entry entry_t;

struct entry
{
  int val;
};

entry_t *entryt_p = (entry_t *)malloc(10 * sizeof(entry_t));

Is there a way I can extract from entryt_p with which size malloc() was called?

glglgl
  • 89,107
  • 13
  • 149
  • 217
Kevin Wilson
  • 153
  • 1
  • 5
  • 1
    Look here why you [don't cast the result of `malloc()`](http://stackoverflow.com/q/605845/296974). – glglgl Feb 11 '14 at 13:47
  • I assume you're retreiving a double pointer or something similar from a library or whatsoever, why don't you just loop until the pointer is NULL? e.g. `for (; p; ++p) { entry_t entry = *p; }` –  Feb 11 '14 at 13:48

2 Answers2

3

There isn't a portable way specified by the language. Some versions of malloc may offer an extension to do it. In general, it's up to your program to keep track.

Adrian McCarthy
  • 45,555
  • 16
  • 123
  • 175
1

There is no way for the user to access this information. Malloc returns a pointer to the address of the memory that was allocated. It is up to the program to keep track of how much was allocated.

If you really don't want to keep track of the size consider using a sentinel value in the last position.

OlivierLi
  • 2,798
  • 1
  • 23
  • 30