开发者

How to use delete[] when pointer outside memory allocation?

Note that the question has been changed and no longer matches the answers

I'm trying to create memory to hold a buffer of floats (here, 4 floats). I've allocated the memory, and all the 4 values in the memory are zero.

The loop of course iterates 4 times, but the 4th time moves ptr to outside the memory that I've allocated. So at the end of the loop I move ptr back to where I allocated the memory, and use delete[].

My question is: Is the entire 4-floa开发者_如何学Pythont buffer being deleted when I call delete[]? (this is obviously what I need!)

int inFramesToProcess = 4;
float *ptr = new float[inFramesToProcess]();

    for(UInt32 i = 0; i < inFramesToProcess; ++i) {
        ptr++;
    }

    ptr -= inFramesToProcess;

delete[] ptr; 


Copy the pointer before you increment it.

int inFramesToProcess = 4;
float *ptr = new float[inFramesToProcess]();
float *ptr_copy = ptr;

    for(UInt32 i = 0; i < inFramesToProcess; ++i) {
        ptr_copy++;
    }

delete[] ptr;

Or just don't use pointers for dynamic arrays, use a vector instead. Then you don't have to worry about deleting.


You can't.

You can only delete the value you get from new. Keep the original pointer.

General rule:

Try hard to avoid modifying pointers at all times, no matter how clever/professional/"brilliant" it looks. There's really no reason to (you're welcome to prove me wrong). Use subscripts instead; they're more readable and easier to debug, and they avoid these kinds of issues.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜