
memory leak: pointer->pointer->pointer->struct
Quote:
> The following works beautifully if x==y, but if they are inequal, I get a
> memory leak... the leak seems a very minor one, and doesnt prevent the code
> from 'working' fine, it just annoys me to have sloppy allocation... was
> wondering if somebody could tell me how I might avoid it.
> #include <stdlib.h>
> typedef struct {
> int dummy;
> int dummy2;
> } * pt_stupid;
pt_stupid is now a new name for the type "pointer to struct { int dummy;
int dummy2; }". It is not clear that that is what you intended.
Quote:
> int main() {
> int i,x=500,y=500;
> pt_stupid **bubba;
bubba is a pointer to a pointer to a pointer to a struct. It is not
clear that that is what you intended.
Quote:
> bubba = (pt_stupid **) malloc(y * sizeof(pt_stupid *));
Better: bubba = malloc(y * sizeof *bubba);
Now check it worked.
Quote:
> for(i=0;i<x;i++)
> bubba[i] = (pt_stupid *) malloc(x * sizeof(pt_stupid));
Better: bubba[i] = malloc(x * sizeof *bubba[i]);
Now check it worked.
In general, use p = malloc(numobjs * sizeof *p) when calling malloc;
the casts are not necessary, don't buy you anything, can in some
circumstances cost you, and look bug-ugly in any case.
Now, as for your bug, it's in your loop.
Quote:
> for(i=0;i<x;i++)
should be
for(i=0;i<y;i++)
n'est-ce-pas? :-)
--
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
--