Reputation:
Why isn't the following example correct? Why doesn't it demonstrate a dangling pointer? My teacher said it doesn't show the dangling pointer. Thanks in advance!
int X = 32;
int *p = &X;
free(p);
*p = 32; //<------Shouldn't this line cause dangling pointer ???
Same thing here. Why doesn't the following example demonstrate a memory leak?
void function(int x){
int *p = &x;
*p = 32;
//shouln't this code show a warning as p was not freed?
}
Upvotes: 3
Views: 591
Reputation: 28664
To cite Wikipedia:
Dangling pointer and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.
Also you should only free memory which was allocated by malloc
or similar allocation functions -it seems that is your confusion in both cases. Basically none of your examples need free
.
An example of dangling pointer would be:
{
char *ptr = NULL;
{
char c;
ptr = &c;
}
// c falls out of scope
// ptr is now a dangling pointer
}
Also if you had example like:
int *p = malloc(sizeof(int));
*p = 9;
free(p); // now p is dangling
Upvotes: 4
Reputation: 75062
This is undefined behavior.
N1256 7.20.3.2 The free function
If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
This code won't cause memory leak by itself because it doesn't throw away any allocated buffer.
Upvotes: 2
Reputation: 1952
Because X is not allocated on heap you cannot free p. To free you must use malloc, calloc or realloc.
Similarly, in second part again variable is on stack which will be automatically cleaned.
Upvotes: 2