Length of a BYTE array in C++

c++

Solution

Given your code:

BYTE *res;
res = (BYTE *)realloc(res, (byte_len(res)+2));

`res` is a pointer to type `BYTE`. The fact that it points to a contiguous sequence of `n` BYTES is due to the fact that you did so. The information about the length is not a part of the pointer. In other words, `res` points to only one `BYTE`, and if you point it to the right location, where you have access to, you can use it to get `BYTE` values before or after it.

BYTE data[10];
BYTE *res = data[2];
/* Now you can access res[-2] to res[7] */

So, to answer your question: you definitely know how many `BYTE`s you allocated when you called `malloc()` or `realloc()`, so you should keep track of the number.

Finally, your use of `realloc()` is wrong, because if `realloc()` fails, you leak memory. The standard way to use `realloc()` is to use a temporary:

BYTE *tmp;
tmp = (BYTE *)realloc(res, n*2);
if (tmp == NULL) {
    /* realloc failed, res is still valid */
} else {
    /* You can't use res now, but tmp is valid. Reassign */
    res = tmp;
}

Problem

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.

Original source