I’m declaring a struct inside my code and then trying to insert it into a data structure that I have written. However, I’m concerned that since I declare the struct inside the function, once the function ends, the data structure will be pointing to garbage. Can anyone help with this?
Here’s the code:
void Class::function() { // do some stuff node newNode; newNode.memAddr = tempNode.memAddr+totalSize; newNode.size = tempNode.size-totalSize; lists[newNode.size>=512?64:(newNode.size>>3)].insert(&newNode); }
Edit: I’m actually trying to re-write malloc, so calling malloc() or new will not work here. Is there some way that I could move this code into the insert method and then make it work in a way that it would not fall out of scope in insert?
It will be out of scope after function returns, yes. That is not valid. You want to allocate it on the heap.
Edit: Unless you copy the memory you point to in insert, of course.