Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29265 Discussions

Unpredictable behavior in internal read

bradlepc
Beginner
815 Views
A user here had a problem with some code to count the number of words in a string. The code is weird, but I don't see an obvious standards violation. However, the behavior is very unpredictable. It runs well on Solaris and Linux, but blows up for about 50% of cases on Windows. It's running in batch so there is limited information available in the way of error messages.

The best theory that I have is that an ERR= should have been specified. Any ideas on what's wrong?

Pete

The code (simplified):

character(132) str_with_words
character(16) :: words(26)

! Code reads in str_with_words here

! Count words on a line
do i = 1, 26
! Next line blows up about 50% of cases
read(str_with_words, *, end=100) words(1:i)
enddo

100 nwords = i-1
0 Kudos
4 Replies
durisinm
Novice
815 Views
Try putting in an iostat variable to capture the error code.

The character*16 words(26) array seems to be too big: 26 elements * 16 characters/element = 416 characters. The read is exhausting the amount of data in the str_with_words character variable. Perhaps trying to read beyond the end of the variable is accessing random pieces of memory.

Mike
0 Kudos
Steven_L_Intel1
Employee
815 Views
Oh, is this such a bad idea! The code is using list-directed read to get character strings, but that only works if there's no punctuation.

END= is the right idea, but ERR= might not be a bad idea either.

Steve
0 Kudos
bradlepc
Beginner
815 Views
I think that's the idea. The author does repeated reads, first for one word, then for two, etc until it tries to read more words than are available. I don't think it should read off the end of string_with_words regardless of the number of characters in the array.

It sure ain't pretty or robust, but it's not obviously wrong. I'm pretty sure I have seen situations before though where Sun trips the END condition while CVF trips ERR. I'm not sure how much wiggle room the standard allows here, but I'll bet there's some.

Steve, good comments. I think the author was attempting to find a way to do this parse regardless of what kind of whitespace separates the words.

In the end, he wrote a better parser.

Pete
0 Kudos
Steven_L_Intel1
Employee
815 Views
The difference you're most likely to find is when you have an ERR= and not an END= and get an end-of-file condition. Some compilers will take the ERR= branch on an EOF, some won't. The standard says not to, and we (Compaq Fortran) changed this behavior a couple of years ago.)

Steve
0 Kudos
Reply