Reputation: 189
I am working on a memory manager for a school assignment. The jist of the assignment is you allocate a large character array, then split that array up into blocks which the client can "allocate" or "free."
Part of the assignment involves header blocks, a little block of information before each block about the block. It basically tracks information about the block. One of the types of header blocks we need to implement is an external header block. For the external header block, instead of storing the header data in the block itself, we need to dynamically allocate a to struct with the header data. The problem is further complicated by the struct having a dynamically allocated label.
My teacher's driver is getting null when it tries to access the data, and when I delete the data, it throws an access violation, probably because I'm not storing the data in the raw memory properly.
In essence, the problem is: I need to dynamically allocate a struct with a dynamically allocated string and then put a pointer to that struct in the first 8 bytes of a block of raw memory.
Here is my current implementation
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;
Upvotes: 0
Views: 137
Reputation: 32727
If I'm following this right, the headerLoc
in you allocation needs to be a pointer to a pointer, since you need to store a pointer to the memory block at address:
MemBlockInfo** headerLoc = reinterpret_cast<MemBlockInfo **>(address);
Then dereference it properly to store header there.
Upvotes: 1