Re: warning: return makes integer from pointer without a cast



Keith Thompson wrote:
Ton 't Lam <ton.tlam@xxxxxxxxxxxxxxxx> writes:
You're right. This is not a question about C, but about flex.

Anyway, the solution is to have:

%option noyywrap

%{
#include <string.h>
#define YY_PROTO(proto) proto
#define YY_DECL char *yylex YY_PROTO(( void ))
%}

%%

[0-9]+ return( (char *) strdup (yytext));

%%

Since you didn't post any context from previous articles, it's
difficult to tell what you changed. Lookup upthread, you originally had:
[0-9]+ return( strdup (yytext));
which you've now changed to
[0-9]+ return( (char *) strdup (yytext));

That silences the warning, but the warning wasn't the problem. Adding
a cast to silence a warning is almost never a good idea. Without
seeing the full C code that's generated from your flex input, it's
difficult to tell, but here's what I think is happening:

strdup returns a result of type char*. Your compiler isn't seeing a
declaration for strdup, so it assumes that it returns int. This alone
invokes undefined behavior. You were lucky enough to get a warning
because you tried to use the result in a context that requires a char*
value (the return statement).

If so, the diagnostic was extremely misleading. Note the sense
of the conversion it complained about: not integer to pointer, but
pointer to integer. If the diagnostic is to be believed, then the
compiler knew [1] that strdup() returns a pointer, and [2] that the
pointer was being converted to an integer in `return'.

As you say, adding a cast to silence a warning is seldom a good
idea, and in this case I suspect it had nothing to do with the cure.
The cure was probably the introduction of the YY_PROTO and YY_DECL
macros, which most likely changed the return type of the generated
C function from `int' to `char*'. If I'm right, then the cast in
the `return' statement is harmless, but useless.

--
Eric.Sosman@xxxxxxx
.



Relevant Pages