看了野指针的概念后,想自己试一下,为什么没有出错呢?
int _tmain(int argc, _TCHAR* argv[])
{
int* test1;
test1 = new int;
*test1 = 33;
delete test1;
*test1 = 23;
return 0;
}*test1果然变成了23,并没有报错,我是在vs2005下调试运行的
int _tmain(int argc, _TCHAR* argv[])
{
int* test1;
test1 = new int;
*test1 = 33;
delete test1;
*test1 = 23;
return 0;
}*test1果然变成了23,并没有报错,我是在vs2005下调试运行的
解决方案 »
- 在MFC对话框界面中如何加载位图图片
- NtOpenSection访问拒绝是什么原因
- 学习C/C++的疑惑,非常的简单还是想不通?
- 用你名字的最后一个字加上"人"字!!!!
- 为何我的select老是返回1呢(附代码)
- 关于CoUninitialize()的问题。
- 问一个关于 SetTimer 的问题
- 怎么从IIS站点上下载文件
- 怎样从WM_KEYDOWN消息的wParam(就是那个虚拟键值)参数获取输入的ASCII码值?有什么函数可以用来做这个转换?
- 怎样让CScrollView的滚动条显示?
- 自绘树控件改变大小时闪的很厉害,有没有好的方法解决闪屏呢?
- 求助!MFC对话框+richedit,如何响应回车?
int* test1;
test1 = new int;
你已经在堆上为它new(分配)了一个空间
然后再做其他new的动作,马上报错. int* test1;
test1 = new int;
*test1 = 23;
delete test1;
*test1 = 23;
int* b = new int;User breakpoint call from code at 0x7c92120e
7C92120B ret 4
7C92120E int 3
7C92120F ret
这里停住.看来误动作了delete的指针,还是会出问题的.
delete只是说那部分内存我不用了,但是指针仍然是指向那部分内存的,因此依然可以访问到。
之前试过,用Dev的编译器,一个完全没有new出来的指针,去delete也不报错的,只是后面会突然死机.
但VC6就马上会报错.
int* test1;
test1 = new int;
*test1 = 33;
delete test1;
*test1 = 23;
int *test2=new int;
return 0;
/*
一、指针变量没有被初始化。任何指针变量刚被创建时不会自动成为NULL指针,
它的缺省值是随机的,它会乱指一气。所以,指针变量在创建的同时应当被初始化,
要么将指针设置为NULL,要么让它指向合法的内存。 二、指针p被new或者delete之后,没有置为NULL,让人误以为p是个合法的指针。
但并没有把指针本身干掉。通常会用语句if (p != NULL)进行防错处理。
很遗憾,此时if语句起不到防错作用,因为即便p不是NULL指针,它也不指向合法的内存块。
*/void main()
{
//for example:
char* p = new char[4]; //传说中的野指针
char* pStr = "123";
strcpy(p,pStr);
delete p; //p又变成了传说中的野指针,且并非指向NULL
if (NULL == p)
strcpy(p,"PASS?");
system("pause");
}
int main()
{
int* test1;
test1 = (int*)malloc(4);
printf("%x\n",test1);
*test1 = 33;
free(test1);
test1=NULL;
if(test1==NULL)
printf("delete\n");
else
*test1 = 23;
printf("%x",test1);
return 0;}
加上test1=NULL.避免野指针。
new的解释
(The new keyword allocates memory for an object or array of objects of type-name from the free store and returns a suitably typed, nonzero pointer to the object.)
new的作用是在堆上给test1分配一个空间,并且把空间地址给test1
delete test1;
delete的解释
(The delete operator deallocates a block of memory. The cast-expression argument must be a pointer to a block of memory previously allocated for an object created with the new operator.)
delete的作用是解除new的内存分配,也就是将内存设置为非占用状态,指针本身并没有进行操作。 所以*test1 = 23只是将23的地址传递给test1
我想楼主所说的会报错可能是如下两种情况
1.出了test1的作用域以后使用test1
2.delete以后又使用test1指向的内存空间(不一定报错)
int* test1;
test1 = new int;
*test1 = 33;
delete test1;
*test1 = 23;
int *test2=new int;
return 0;
没有错误,单步跟踪了下,分配空间也成功了
就算delete的内存未给其他使用,写了后也会错的,而且是莫名其妙的错。
int* test1;
test1 = new int;
*test1 = 23;
delete test1;
*test1 = 23;
int* b = new int;
最后一句 int* b = new int;时,之前test1的地址应该未有用到,但还是飞出一个错误来。
有时没有出现错误,但当我关闭整个软件时,才报出错误。