The accepted answer is incorrect. This will lead to memory leaks.
Internally, yy_scan_string calls yy_scan_bytes, which in turn calls yy_scan_buffer.
yy_scan_bytes allocates memory for a COPY of the input buffer.
yy_scan_buffer works directly with the supplied buffer.
With all three forms, you MUST call yy_delete_buffer to release buffer status information (YY_BUFFER_STATE).
However, with yy_scan_buffer you avoid internal allocation / copy / free internal buffer.
The prototype yy_scan_buffer does NOT accept const char *, and you SHOULD NOT expect the contents to remain unchanged.
If you have allocated memory to hold your string, you are responsible for freeing it AFTER you call yy_delete_buffer.
Also, don't forget that yywrap returns 1 (nonzero) when you parse ONLY this line.
The following is an example of COMPLETE.
%% <<EOF>> return 0; . return 1; %% int yywrap() { return (1); } int main(int argc, const char* const argv[]) { FILE* fileHandle = fopen(argv[1], "rb"); if (fileHandle == NULL) { perror("fopen"); return (EXIT_FAILURE); } fseek(fileHandle, 0, SEEK_END); long fileSize = ftell(fileHandle); fseek(fileHandle, 0, SEEK_SET); // When using yy_scan_bytes, do not add 2 here ... char *string = malloc(fileSize + 2); fread(string, fileSize, sizeof(char), fileHandle); fclose(fileHandle); // Add the two NUL terminators, required by flex. // Omit this for yy_scan_bytes(), which allocates, copies and // apends these for us. string[fileSize] = '\0'; string[fileSize + 1] = '\0'; // Our input file may contain NULs ('\0') so we MUST use // yy_scan_buffer() or yy_scan_bytes(). For a normal C (NUL- // terminated) string, we are better off using yy_scan_string() and // letting flex manage making a copy of it so the original may be a // const char (ie, literal) string. YY_BUFFER_STATE buffer = yy_scan_buffer(string, fileSize + 2); // This is a flex source file, for yacc/bison call yyparse() // here instead ... int token; do { token = yylex(); // MAY modify the contents of the 'string'. } while (token != 0); // After flex is done, tell it to release the memory it allocated. yy_delete_buffer(buffer); // And now we can release our (now dirty) buffer. free(string); return (EXIT_SUCCESS); }