dbansal said:
Drop the pointless obfuscatory cast.
And that one.
free(ptr);
ptr = NULL;
This is Interesting..! I am just putting small code to check some
stuff.
/* Start test1.c */
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
char *p;
char*q;
p=(char *) malloc(100);
/* I should do memset but ... */
strcpy(p,"raxit sheth");
q=p;
printf("\nP=%p : %s",p,p);
printf("\nQ=%p :%s",q,q);
fflush(stdout);
free(p);
/* p=NULL; */
printf("\n AFTER FREE ");
printf("\nP=%p : %s",p,p);
printf("\nQ=%p : %s",q,q);
return 0;
}
/* end */
output on linux box (valgrind shows double free error)
$gcc -g3 -Wall test1.c -o test1
$./test1
P=0x8049800 : raxit sheth
Q=0x8049800 :raxit sheth
AFTER FREE
P=0x8049800 : raxit sheth
Q=0x8049800 : raxit sheth
Now Uncommented p=NULL in above code. Output is
P=0x8049810 : raxit sheth
Q=0x8049810 :raxit sheth
AFTER FREE
P=(nil) : (null)
Q=0x8049810 : raxit sheth <----important
I think (correct me if I am wrong, I am learning here.)
1.this technique is useful in some case but not in all where pointer
assignment is doing like this way. q is pointing to same memory
location as of p before free, and doing p=NULL is not helpful for q.
2. normally sequence,
p=NULL;
malloc,
memset,bzero or equivalent
use of memory
free
May be p=NULL.
can be
p=NULL;
malloc,
memset,bzero or equivalent
use of memory
memset,<---Some practical limitation. I may not be knowing what
size to free and howmany bytes to memset.
free
(p=NULL ?)
any opinion on this ? Adv/Disadv/limitation/ ?
--Raxit Sheth