这是我的代码:
int *p;
p=4;
printf("p is %p\n",p);
free(p);
//need p=NULL but I don't
int *q;
q=5:
printf("q is %i",*q);
然后出现错误。 我只需要解释。
答案 0 :(得分:3)
int *p;
是指向int的指针。
p = 4;
使其指向地址0x4
free(p);
尝试取消分配地址0x4
基本上,您正在尝试释放无法释放的资源。
int *q;
q = 5;
将q指向地址'0x5;
*q;
从0x5
地址读取,很可能会崩溃。 (此地址也未对齐)。
指针不是整数...您编写的程序显示出对什么是指针以及为什么/应该如何使用它们缺乏了解。
答案 1 :(得分:0)
Int *p; // You had better use int* p = NULL; we don't like wild pointers
//p = new int;
p=4; // I guess you want put the value of 4 to a variable, so *p = 4;
printf("p is %p\n",p);// printf("p is %d\n",*p);
free(p);//just correct in theory, no one can tell what happens in reality.
/*
if ( NULL != p )
{
delete p;
p = NULL;
}
*/