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?
Since
buffer
is a pointer (not an array), thesizeof
operator returns the size of a pointer, not the size of the buffer it points to. There is no standard way to determine this size, so you have to do the bookkeeping yourself (i.e. remember how much you allocated.)BTW, it's the same for
Interestingly,
is 14. Can you guess why?
sizeof is used to calculate size for actual objects, not pointers for objects in memory. It returns size of structs or primitives. I mean it will work, but will give you size of the pointer, not the structure it points to. To get the length of any sort of array use :
For GNU glibc:
DESCRIPTION
You cannot make such a test. It is your own responsibility to remember how much memory you allocated. If the buffer is given to you by someone else, demand that they pass the size information as well, and make it their responsibility to pass the correct value or have the program die.
buffer
is just a pointer without size information. However the malloc() routine will hold the size of the allocation you made so when you free() it, it frees the right amount of space. So unless you want to dive in the malloc() functionality, I recommend you just save the size of the allocation yourself. (for a possible implementation, see the example in the other API answer).Use the API and not malloc/free and you can't go wrong.