I'm trying to write a program that simulates a small memory manager. By the bounds of the problem I have
1 2 3 4 5 6 7 8 9 10 11 12 13
namespace myNamespace {
constint MAX = 65536;
char memory[MAX];
//initialize the memory
void init();
//allocates memory from memory[] and returns a pointer
//to the position in the array
void* allocate(int size);
...
}
Is there a way to overload an assignment operator such that
calls my own function, instead of the standard? I'm most worried about the second line, since I'm trying to prevent data from overwriting unallocated memory.
I feel like this is impossible since the assignment operator is non-static member, but I can't find anything that tells me one way or another. Help?
You don't need to overload =operator. You have to overload allocate function (which you can't really do the way you want to). you could overload 'new' but that would be a bad idea if you ever needed to call the real one...
You should write a separate function to do this. Something like void* AllocMemory(int size).
Good luck
I'm sorry, I guess what wasn't very clear. I've got the allocate function created, I don't need to worry about that. I'm not using "new" or dynamically allocating memory--the "allocate" function (which I've already written) sets aside "size" number of bytes from the memory[] array as "allocated memory," while the rest of the array is "unallocated memory." The kind of thing I'm trying to prevent is:
1 2
int* ptr = (int*)allocate(1);
ptr=3;
Unless ints are only one byte long on your system, the assignment here is going to overrun the memory allocated for it. I could always create a "checker" function, like
Could you use a template of this function and have the template determine the size correctly without the user potentially messing up? Doing a template would also mean being able to output a pointer of the type you are inputting rather than having to cast it after allocating the space.
Unfortunately not...I have to use the function as defined in the first post. Good idea though!
At this point, I think I'm just going to define a checkForOverruns function. It's not as elegant as overriding an assignment operator, but it looks like the best I'm going to be able to do.