user17804723
user17804723

Reputation:

Why is the pointer not free and doesn't it bring me same value of a variable?

In the below code I free the pointer ptr but still *ptr retuns me the same value. If I free the variable then it should give me some garbage value but it didn't.

#include <stdio.h>
#include<stdlib.h>
int main()
{
    int a=5;
    int *ptr=&a;
    printf("%d, %d \n",a,*ptr);
    free(ptr);
    printf("%d, %d \n",a,*ptr);
    return 0;
}

Upvotes: 0

Views: 486

Answers (4)

Eric Postpischil
Eric Postpischil

Reputation: 223795

free(ptr) does not change the value of ptr. It merely asks the memory management software to release the reservation of the memory that ptr points to. Calling a function passes the value of its arguments; it does not pass any information about the identity of its arguments, so free does not receive any information about the ptr variable that would allow free to change that variable. It receives only a copy of its value.

Further, the behavior of free is defined only when it is passed an address that was previously returned by malloc or a related routine. It is not defined when given the address of a named object, such as &a.

Upvotes: 1

aulven
aulven

Reputation: 531

If you haven't allocated the memory yourself as John Bode answered, you cannot free it.

But even if you did allocate the memory, the free does not erase the contents of the memory block pointed by your pointer, it merely allows that block of memory to be used by something else, hence it "frees" it, not "erase"s. If nothing else happens to write to that memory block after you freed it, your content will still be sitting there.

Upvotes: 2

Raildex
Raildex

Reputation: 4765

Two things:

First: the value ptr contains is not memory allocated with malloc.
For every malloc, there must be a free. Since you are free()ing memory you don't allocate with malloc, you are invoking Undefined Behaviour (C and C++ programmers love this term)

Second: Since you are invoking Undefined Behaviour, the behaviour can be anything. A seemingly correct behavouring program can be in the territory of undefined behaviour. You are simply lucky that you receive the same value over and over. On other systems your program could crash, kill an innocent grandma or simply push the delete button of the universe.

Upvotes: 0

John Bode
John Bode

Reputation: 123568

You can only free memory that has been allocated by malloc, calloc, or realloc - you cannot use it to deallocate memory associated with an auto variable (the behavior is undefined):

int *ptr = malloc( sizeof *ptr );
*ptr = 5;
printf( "%d\n", *ptr );
free( ptr );

Upvotes: 2

Related Questions