How to determine the size of an allocated C buffer?

godzilla picture godzilla · May 17, 2012 · Viewed 62.6k times · Source

I have a buffer and want to do a test to see if the buffer has sufficient capacity I.e. find number of elements I can add to the buffer.

char *buffer = (char *)malloc(sizeof(char) * 10);

Doing a

int numElements = sizeof(buffer); 

does not return 10, any ideas on how I can accomplish this?

Answer

Vitaly picture Vitaly · Jul 11, 2013

For GNU glibc:

SYNOPSIS

#include <malloc.h>
size_t malloc_usable_size (void *ptr);

DESCRIPTION

The malloc_usable_size() function returns the number of usable bytes in the block pointed to by ptr, a pointer to a block of memory allocated by malloc(3) or a related function.