I have a program in C++ that has a BYTE array that stores some values. I need to find the length of that array i.e. number of bytes in that array. Please help me in this regard.
This is the code:
BYTE *res;
res = (BYTE *)realloc(res, (byte_len(res)+2));
byte_len is a fictitious function that returns the length of the BYTE array and I would like to know how to implement it.
Given your code:
resis a pointer to typeBYTE. The fact that it points to a contiguous sequence ofnBYTES is due to the fact that you did so. The information about the length is not a part of the pointer. In other words,respoints to only oneBYTE, and if you point it to the right location, where you have access to, you can use it to getBYTEvalues before or after it.So, to answer your question: you definitely know how many
BYTEs you allocated when you calledmalloc()orrealloc(), so you should keep track of the number.Finally, your use of
realloc()is wrong, because ifrealloc()fails, you leak memory. The standard way to userealloc()is to use a temporary: