This question already has answers here:
Can I delete[] a pointer that points into an allocated array, but not to the start of it?
                                
                                    (7个答案)
                                
                        
                                2年前关闭。
            
                    
int main(){

int *p=new int[5];

//case 1: delete p;
//case 2: p++;delete[] p;


return 0;
}


如果分别使用情况1和情况2,会发生什么?

最佳答案

会发生什么


情况1:不确定的行为。

调用p并没有返回new(而是由new[]代替),因此delete p;是UB。



情况2:不确定的行为。

调用p+1未返回new[],因此p++;delete[] p;是UB。

关于c++ - 如果在增加指针后删除数组,会发生什么? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42362882/

10-12 23:20