AD1

Saturday, 3 June 2017

What is dangling pointer

The following code snippet illustrate the idea of dangling pointers


#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
int *p=(int*)malloc(sizeof(int));
*p=1;
/*
* now p is an integer pointer pointes to space(4 bytes)allocated
* by malloc function , also the allocated space is initilized by 1
*/
cout<<*p<<endl;//result will be 1
//now we will free or deallocate reserved 4 bytes
free(p);
/*
* now p is a dangling pointer , pointes to deallocated space
* so data at this pointer is garbage
*/
cout<<*p;// output will be garbage
return 0;
}
view raw dangling.cpp hosted with ❤ by GitHub

No comments:

Post a Comment