Yay For Leakage
Spot the intentional *cough* error in the following C code:
If you don't do C, all you need to understand is that I'm very stupid.mystruct *create(int bar) {
mystruct *a;
a = (mystruct *) malloc(sizeof(mystruct));
a->foo = bar;
return a;
}
mystruct *add(mystruct *a, mystruct *b) {
return create(a->foo + b->foo);
}
int main() {
mystruct *leaky_goodness;
leaky_goodness = add(create(1), create(2));
printf("I leaked all over myself: ", leaky_goodness->foo);
return 0;
}
If you do do C and you still don't see it, take a look at what happens to the three mystructs I create... Oh, and at least I noticed it :)
Comments
Without doing much C any longer, you malloc a lot of things that you never free again - even though you lose the references. Isn't that it? :) .. I've switched to coding mainly C++, which makes this a little easier - or, as I've been forced to at the university, java, which makes you use lots and lots of temporary classes - They will, after all, be garbage-collected anyway *cough* ;o)
Java sucks, C++ is for girls - real men program in C. And Perl and BASIC, they're pretty hardcore too. Oh, and Javascript can be pretty sweet at times.
And yes, I'm allocating mystructs to hold 1, 2 and 3, I only end up with a pointer to the mystruct holding 3, and I lose the pointers to the other two because they were anonymous.
Leave a comment
- Add a comment - it's quick, easy and anonymous