"Yang Lee" <> wrote:
> I have two char pointers
>
> char *a,*b;
> a=(char *)malloc(10);
> b=a; /*******/
>
> so both pointers are looking at same mamory location
It's rude to point, especially at mammary locations.
> strcpy(a,"gates");
> printf("%s",b);
>
> Now I free pointer b;
> free(b);
All good so far. Now the value of both a and b is no longer valid.
> Then will pointer a be in existance or it will be also freed.
> or if I free pointer a then will b point to same location.
Pointer a and b both store the same memory address. You have
freed the memory at that address, so neither a nor b are now
valid. You must not attempt to free(a) now.
> Also
>
> a=(char *)malloc(10);
> strcpy(a,"gates");
> free(a);
> printf("%s",a);
Whoops -- you just used the invalid pointer value in a, so
your program has undefined behaviour. Anything could happen.
> this still prints "gates " why is this happening
> even after freeing the memory?
Anything could happen, including the possibility that the
memory still contains what was in it before -- for now --
but it may get reallocated or written over, some time in
the future, so you should not rely on this behaviour.
> should I write a=NULL;
Only if setting it to a null pointer makes sense in your
particular case. If you have finished with the variable
then there is no need to change its value. If you intend
to re-use the variable then it must be set to a valid
pointer value at some point; if you can be sure that you
will not attempt to read from it before that point, you
can leave it alone until you set it to a correct value.
--
Simon.