【问题标题】:Insert a pointer into raw memory将指针插入原始内存
【发布时间】:2016-01-17 00:42:55
【问题描述】:

我正在为一项学校作业开发内存管理器。任务的要点是分配一个大字符数组,然后将该数组拆分为客户端可以“分配”或“释放”的块。

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

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

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

这是我当前的实现

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;

【问题讨论】:

  • strlen(label) 太短了一个字符。

标签: c++ memory memory-management


【解决方案1】:

如果我正确地遵循这一点,则分配中的headerLoc 需要是指向指针的指针,因为您需要在地址处存储指向内存块的指针:

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

然后正确地取消引用它以将标题存储在那里。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多