0

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?

1 Answer 1

0

I think Visual Studio is storing the result of "entries[n*spacing]" in a temporary, and then returning a reference to the temporary.

That is incorrect. Assuming entries is defined as double entries[]; or double* entries, then entries[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*spacing being outside the array bounds, or the whole entries being deallocated by the time the reference is accessed.

Sign up to request clarification or add additional context in comments.

1 Comment

Further inspection showed that entries was invalid. Thanks K-ballo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.