将指针插入原始内存

时间:2016-01-17 00:42:55

标签: c++ memory memory-management

我正在为一所学校作业的记忆经理工作。赋值的作用是你分配一个大字符数组,然后将该数组拆分成块,客户端可以分配"分配"或者"免费。"

部分分配涉及标题块,每个块之前的一小块信息块。它基本上跟踪有关块的信息。我们需要实现的标头块类型之一是外部标头块。对于外部头块,我们需要动态地将头数据存储到块本身中,而不是将头数据存储在块本身中。具有动态分配标签的结构使问题进一步复杂化。

我的老师的驱动程序在尝试访问数据时变为空,当我删除数据时,它会引发访问冲突,可能是因为我没有正确地将数据存储在原始内存中

本质上,问题是:我需要动态分配一个带有动态分配字符串的结构,然后在原始内存块的前8个字节中放置一个指向该结构的指针。 < / p>

这是我目前的实施

char* newString = new char[strlen(inputString)];
//Copy the label passed into this fx into the allocated memory
strcpy(newString, inputString);

//Allocate and initalize the struct
headerStruct* pHeader = new headerStruct;
pHeader->active = true;
pHeader->string = newString;

//Save the first 8 bytes of my block of memory as a headerStruct*
headerStruct* hAddress = reinterpret_cast<headerStruct(*)>(address);
//Make the first 8 bytes point to the recently allocated struct
hAddress = pHeader;

1 个答案:

答案 0 :(得分:1)

如果我遵循这个权利,你分配中的headerLoc需要是指向指针的指针,因为你需要在地址处存储指向内存块的指针:

MemBlockInfo** headerLoc = reinterpret_cast<MemBlockInfo **>(address);

然后正确取消引用它以存储标题。