I was trying to implement flex and bison when this loop returned segmentation fault whith core dumped With the first file it worked fine but the next file crashed and printed into terminal segmentation fault.
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("./Corpus")) != NULL)
{
while ((ent = readdir (dir)) != NULL)
{
if ((strcmp(ent->d_name,".") != 0) && (strcmp(ent->d_name,"..") != 0))
{
printf("%s\n",ent->d_name);
yyin = fopen(ent->d_name,"r");
yyparse();
}
}
closedir (dir);
}
else
{
// could not open directory
perror ("");
return EXIT_FAILURE;
}
If you are using a reasonably recent version of flex
, there is nothing wrong with switching input files in the way you do it. However, without seeing more code, it is impossible to know for certain what the problem is.
One obvious problem is that you do not check the value of yyin
after the call to fopen
. If the open fails (which is likely, see below), then yyin
will be NULL
and that will certainly create a segfault when flex
attempts to read.
Also, you don't seem to be closing yyin
, which will leak file descriptors. This should not be a problem on the second file, but it will eventually cause the open to fail for lack of file descriptors.
The problem with the fopen
is that ent->d_name
is just the basename of the file, without any path. So fopen
will search for the file in the current working directory. However, the directory being read is ./Corpus
, which is a subdirectory; unless the file is duplicated between Corpus and the main directory, the file will not be found.
For the benefit of commentators, the Flex manual states:
If the scanner reaches an end-of-file, subsequent calls are undefined unless either yyin is pointed at a new input file (in which case scanning continues from that file)… Essentially there is no difference between just assigning yyin to a new input file or using yyrestart() to do so; the latter is available for compatibility with previous versions of flex, and because it can be used to switch input files in the middle of scanning.
It is also possible that the segfault is independent of file handling. It would be best to use a debugger to determine where exactly the segfault occurs.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다