该代码将做什么? (内存管理) [英] What would this code do? (memory management)

查看:69
本文介绍了该代码将做什么? (内存管理)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char *p = new char[200];
char *p1 = p;
char *p2 = &p[100];
delete [] p1;

这不是测试还是我实际上需要知道的任何东西:)

Btw this is not a test or anything i actually need to know this :)

推荐答案

 // allocate memory for 200 chars
 // p points to the begining of that 
 // block
 char *p = new char[200];
 // we don't know if allocation succeeded or not
 // no null-check or exception handling

 // **Update:** Mark. Or you use std::no_throw or set_new_handler. 
 // what happens next is not guranteed

 // p1 now points to the same location as p
 char *p1 = p;

 // another pointer to char which points to the
 // 100th character of the array, note that
 // this can be treated as a pointer to an array
 // for the remaining 100-odd elements
 char *p2 = &p[100];

 // free the memory for 200 chars
 delete [] p1;

 // **Update:** Doug. T
 // [...] p and p2 are now pointing to freed memory 
 // and accessing it will be undefined behavior 
 // depending on the executing environment.

这篇关于该代码将做什么? (内存管理)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆