tags:

views:

102

answers:

4

I'm writing some terrible, terrible code, and I need a way to put a free() in the middle of a statement. The actual code is:

int main(){
    return printf("%s", isPalindrome(fgets(malloc(1000), 1000, stdin))?"Yes!\n":"No!\n") >= 0;
    // leak 1000 bytes of memory
}

I was using alloca(), but I can't be sure that will actually work on my target computer. My problem is that free returns void, so my code has this error message:

error: void value not ignored as it ought to be

The obvious idea I had was:

int myfree(char *p){
    free(p);
    return 0;
}

Which is nice in that it makes the code even more unreadable, but I'd prefer not to add another function.

I also briefly tried treating free() as a function pointer, but I don't know if that would work, and I don't know enough about C to do it properly.

Note: I know this is a terrible idea. Don't try this at home kids.

EDIT: Thanks a lot guys, I got it working by changing my one-line isPalindrome() function to this:

return (...)?(calls == 1?free(pLeft),1:1):(calls == 1?free(pLeft),0:0);

(calls is keeping track of recursion depth)

No more memory leaks!

+8  A: 

I don't know quite where you're going to shoehorn this in but if you need an expression that frees a pointer p as a side effect and evalutes to 0 then you can just use this.

(free(p), 0)
Charles Bailey
Exactly what I was looking for.
Brendan Long
+3  A: 

A comma operator, maybe?

char *buf;
printf("%s", isPalindrome(fgets(buf = malloc(1000), 1000, stdin))? (free(buf), "Yes!\n"):(free(buf), "No!\n") >= 0;

Not sure whether you're "allowed" to use a variable, though.

Or define a wrapper for isPalindrome which frees its parameter:

printf("%s", isPalindrome_free(fgets(buf = malloc(1000), 1000, stdin))? "Yes!\n":"No!\n")) >= 0;
Steve Jessop
+1  A: 

Turn it inside out

  1. Do the printf inside ur isPalindrome function.

  2. Inside isPalindrome Call free() after the printf and return from the function.

  3. Main() remains the one-liner it is isPalindrome()

CVS-2600Hertz
Thanks a lot, I couldn't have made it one line without this.
Brendan Long
+1  A: 

You can use , operator to chain function calls, i.e.:

int main(){
    return printf("%s", isPalindrome(fgets(malloc(1000), 1000, stdin)) ? 
                 (free(p), "Yes!\n") : (free(p), "No!\n")) >= 0;
}

assuming you assign allocated buffor to p first.

pajton