【发布时间】:2015-10-30 09:27:14
【问题描述】:
我有一个小问题。 我正在用 Visual C++(VS 2013)编写一个程序。我想制作这样的工作代码。
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);
}
它工作,目标分配和初始化。但是当我从这个函数返回时,目标链接到NULL。
例如:
...
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
...
Blob 的样子
class Blob
{
public:
...
BYTE* Data;
DWORD Length;
...
}
函数返回后我可以做些什么来保存新分配的范围? 一种解决方案是创建一个新对象 Blob 并像这样分配其字段:
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;
}
在这种情况下,一切正常。但是,如果我只想获得分配内存的 BYTE* 指针怎么办? 可能是我不明白什么?
【问题讨论】:
-
你做错了。停止使用指针和原始数组,学习使用标准容器,例如
std::vector。 -
我使用 WinCrypt。它使用 BYTE* 数组
-
由于WinCrypt既不分配也不释放缓冲区,你可以毫无问题地传递
std::vector<BYTE>的内容(使用myvector.data()或&myvector[index])。
标签: c++ pointers visual-studio-2013 scope