I have a little problem. I am writing a program in Visual C++ (VS 2013). And I want to make work code like this.
void Blob::ReadBytes(BYTE* target, DWORD position, DWORD readLength)
{
// check
if (position + readLength > this->Length)
{
// clean if it allocated memmory, because need return nullptr
target = static_cast<BYTE*>(realloc(target, 0));
return;
}
// allocate memmory
target = static_cast<BYTE*>(realloc(target, readLength));
memmove(target, this->Data + position, readLength);
}
It works, target allocated and initialized. But when I return from this function, target links to NULL
.
for example:
...
Blob b;
BYTE* data = new BYTE[4];
data[0] = 'a';
data[1] = 'b';
data[2] = 'c';
data[3] = 'd';
b.Append(data, 4); // Add data to Blob
BYTE* bytes = nullptr;
b.ReadBytes(bytes, 0, 3);
// There bytes = NULL
...
Where Blob is like
class Blob
{
public:
...
BYTE* Data;
DWORD Length;
...
}
What I can do to save new allocated scope after function returns? One of solutions is to make a new object Blob and allocate its field like this:
Blob Blob::ReadBytes(DWORD position, DWORD readLength)
{
Blob blob;
// check
if (position + readLength > this->Length)
{
blob.Data = static_cast<BYTE*>(realloc(blob.Data, 0));
return Blob();
}
// allocate memmory
blob.Data = static_cast<BYTE*>(realloc(blob.Data, readLength));
memmove(blob.Data, this->Data + position, readLength);
blob.Length = readLength;
return blob;
}
And in this case all work well. But what if I want get only BYTE* pointer with allocated memory? May be I do not understand something?