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!

+2


a source to share


4 answers


I don't know where you are going to do this, but if you need an expression that frees the pointer p

as a side effect and evalutes to 0, you can just use that.



(free(p), 0)

      

+10


a source


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;

      

+3


a source


Turn it inside out

  • Make printf inside ur isPalindrome function .

  • Inside isPalindrome Calling free () after printing and returning from the function.

  • Main () remains one line isPalindrome ()

+1


a source


You can use the operator ,

to call a chain of functions, that is:

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

      

assuming you assign the dedicated buffer first p

.

+1


a source







All Articles