TL;DR Pointers do not store any information regarding the allocated memory size. So, there is not straightway API kind of thing using which we can determine the allocated size.
However, some dynamic memory allocation libraries provide some options to actually fetch the information regarding the allocated size, but that's non-standard and heavily implementation dependent.
That said, you can think of an approach where you can explicitly mark the end of the data (check about the sentinel value concept) stored into the dynamically allocated memory (thus, essentially, marking the end of the allocated memory) but then also, it's something you have to take care of.
Please remember. as very rightly mentioned by Mr. Paul R, this sentinel value approach can be quite inefficient and there can be many limitations to this approach, like
- You cannot have the sentinel value as one of the legit values.
- In case, somehow the sentinel value does not appear at the very end of the allocation, it may provide wrong information about the allocated size.
- You're always allocating some memory (to put the sentinel) which is not being used effectively.
and so on.
IMHO, best approach will be, keep the track of the size of allocation in a separate variable and pass that around with the pointer, as and when necessary.