1

Possible Duplicate:
Any function to query the size of an allocated block?
Getting the size of a malloc only with the returned pointer

Let us say that I let the user specify the number of bytes to be passed to an int *x using the malloc function. Is there a way to determine the actual number of bytes that were assigned to the integer?

Community
  • 1
  • 1
Matthew
  • 4,477
  • 21
  • 70
  • 93

1 Answers1

3

There is no portable way. The language standard doesn't provide any means to do that.

Each implementation needs to keep track of the sizes of the malloced memory of course somehow, to be able to correctly free it, so it may offer a means to get at that information. In glibc's malloc.h, there is a prototype

size_t malloc_usable_size(void *);

that allows you to get at the number of usable bytes allocated for the passed-in pointer, but that is often larger than the number of bytes requested in the malloc call. Other implementations may offer other means to get at that kind of information.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431