The following code snippet illustrate the idea of dangling pointers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
No comments:
Post a Comment