Handling void function as value
I'm writing awful, awful code, and I need a way to put free () in the middle of a statement. Actual code:
int main(){
return printf("%s", isPalindrome(fgets(malloc(1000), 1000, stdin))?"Yes!\n":"No!\n") >= 0;
// leak 1000 bytes of memory
}
I have used alloca () but I cannot be sure what will actually work on my target computer. My problem is that free is returning void, so my code has this error message:
error: void value not ignored as it ought to be
The obvious idea:
int myfree(char *p){
free(p);
return 0;
}
It's good that it makes the code even more unreadable, but I'd rather not add another function.
I also briefly tried to treat 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 right.
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:
return (...)?(calls == 1?free(pLeft),1:1):(calls == 1?free(pLeft),0:0);
(calls keep track of recursion depth)
More memory leaks!
a source to share
A comma operator, perhaps?
char *buf;
printf("%s", isPalindrome(fgets(buf = malloc(1000), 1000, stdin))? (free(buf), "Yes!\n"):(free(buf), "No!\n") >= 0;
Not sure if you are allowed to use a variable.
Or define a wrapper for isPalindrome that releases its parameter:
printf("%s", isPalindrome_free(fgets(buf = malloc(1000), 1000, stdin))? "Yes!\n":"No!\n")) >= 0;
a source to share