I have a class v which dynamically allocates an array of doubles. Entries is a pointer to the beginning of this array. Spacing allows me to skip over entries, for example, if I wanted to only consider every third entry, spacing would be 3.
double& v::operator[] (const int n) {
return entries[n*spacing];
}
This subscript operator compiles but causes heap corruption. Based on my web searches, I think Visual Studio is storing the result of "entries[n*spacing]" in a temporary, and then returning a reference to the temporary. Heap corruption occurs when I try to write to this reference to deallocated memory.
Does anyone have ideas for a workaround?
That is incorrect. Assuming
entriesis defined asdouble entries[];ordouble* entries, thenentries[i]returns a reference and is that reference that gets returned by your subscript operator.The source of your problem is somewhere else. Perhaps in
n*spacingbeing outside the array bounds, or the wholeentriesbeing deallocated by the time the reference is accessed.