diary : entry

Yay For Leakage

19th November 2003 at 18:21
Spot the intentional *cough* error in the following C code:
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 don't do C, all you need to understand is that I'm very stupid.

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

  1. 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)
    Mihtjel20th November 2003 at 07:26
  2. 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.
    radiac20th November 2003 at 08:05
  3. 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.
    radiac20th November 2003 at 08:06

Add a comment

Name:(required)
E-mail:(will not be made public)
Website:
Comment:
Beef cut: Your beef cut of the day is:


Please enter it below:

Thank you for proving you are a human, not a spammer!
 

Links