Determining presence of prototype with correct return type
- by R..
Here's a random problem in C black magic I just came up with:
Write a function that returns 1 if malloc has been prototyped to return a pointer type and 0 if malloc has a return type of int (either implicitly or due to wrong prototype), without invoking any implementation-defined or undefined behavior.
I believe it's solvable, but I haven't worked out the solution. Note that calling the function cannot be necessary and in fact is not possible since calling a function with the incorrect prototype is undefined behavior. I have some ideas for ingredients but I think it makes for a better puzzle (and possibly more diverse ideas) if I leave them out for now.
I don't need the solution for any immediate use, but it could be handy in configure scripts and such.
Update: A better example of the usefulness (with strdup instead of malloc):
#undef strdup
#define strdup(x) (strdup_has_proto ? strdup((x)) : my_strdup((x)))
i.e. being able to implement X_has_proto as an expression at the source level could be a portable way to use functions which a system might or might not have, and fall back on a local replacement, without needing any separate configure step.