I am experiencing memory leaks using pointer math to traverse my indexed heap. What is the best way to calculate object size and move from one index to another?
In arr.h, I have
-node struct. Each node has 3 ints, and a pointer to its child.
-a function pop, that removes the last node of the object.
-pointer to head and tail node (first and last elements of heap)
-this const that holds sizeof(head)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class arr {
public:
...
void pop(); //remove last element
...
private:
struct node {
int index;
int vertex = 0;
int value;
node* child;
};
node* head;
node* tail;
const ptrdiff_t nodedist = sizeof(head);int size = 0;
};
In arr.cpp, I decrement tail pointer by nodedist, to make the second to last node the new end of the object.
i was more concerned that const ptrdiff_t nodedist = sizeof(head);
wasn't a good way to store the size of a node. But from your response, that bit is good.
It isn't a way to store the size of a node. It's the way to store the size of a pointer-to-node. Whether it's valid for your purposes or not depends on things we can't see (although I tend to think it is not.) I just skimmed enough to see you don't have enough information to begin to solve your issue.
[Edit: Actuallly, it definitely is not adequate. When you use pointer math, the amount the pointer should be incremented is already accounted for by the compiler.]
when you say "size of a pointer-to-node", is that the distance from one node to the next?
No. When I say "size of a pointer-to-node" it could be interpreted as "the distance from one pointer-to-node to the next", but it definitely is not the distance from one node to the next.
But, see the edit above. Pointer math already accounts for the "distance" based on the type of the pointer.
I thought of this solution. I left nodedist as non-const in the header file, and didn't define it. so ptrdiff_t nodedist;
I will define it once object size is greater than 0.
1 2 3 4 5 6 7
//idx == 1 means that head has a child.
//set nodedist to be (head's child - head)
if (idx == 1) {
head->child = NewNode;
nodedist = head->child - head;
cout << nodedist << endl;
}
This seems to do what I want. but the cout << nodedist << endl; returns some garbage on the screen.