Re: malloc/free aimple question!
Hello, David and Ben!
I am freeing p and leaving x alone. I was also tempted toset x to null, but
thats dangerous too... no!
Its just that in my real program, x and p are members of two different
structures which are typedefed in a header.
But my bug doesn't seem to point to a free() problem. I have to water down
the whole code again to see where this will end up. I have two winprocs. When
I go from the first winProc to the second one, and come back to the first
one, everything is ok. If I do the same thing but this time I remove a line
in the second winProc which has nothing to do with mallocing or freeing, when
I get back to the 1st winProc, and press a button twice... on the second
press, the program bombs catastrophically! I have a funny feeling I will
learn a good lesson on this one!
At this point I really can't give any usefull information until I get down
to what is really going on.
Thanks guys for your help. I will repost if I don't understand something else.
--
Best regards
Roberto
"Ben Voigt [C++ MVP]" wrote:
Robby wrote:
Hello,
Please view the code below:
========================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int a;
long *p, *x;
p = malloc(10 * sizeof(long));
x = p;
for(a=0; a<9; a++)
{
// do stuff with x
*(x+a) = a;
}
free(p);
// other code here...
return 0;
}
===========================
In this case, does x have to be freed also?
You should not call free(x). But both x and p become invalid when you call
free(p), so don't use x any more either.