This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: Another reason to use win32-api
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
I discovered a minor little bit of nastiness with both our own win32-api and Ruby's Win32API library. Consider the following bit of code:
require 'Win32API'
strtok = Win32API.new('mvscrt', 'strtok', 'PP', 'P')
string = "A string\tof ,,tokens\nand some more tokens";
seps = " ,\t\n";
puts "Tokens:"
token = strtok.call(string, seps)
while token
puts token
token = strtok.call(nil, seps)
end
This produced the following result:
C:\>ruby strtok.rb
Tokens:
A
string
of
tokens
and
some
more
tokens
... in `call': NULL pointer given (ArgumentError)
I blows up at the end. Why? Because of the way strtok works. It modifies the original string, moves the pointer to the next token in the string and eventually reaches the end of the string. Then it tries to read one more time, fails, and breaks out of the loop.
It's the bit where it tries to read one more time with the file pointer already at the end of the string that the trouble occurs. Since it's already at the end of the string it's now a NULL pointer, and the attempt to convert it to a Ruby string causes the error you see above.
The fix? Simply check the return pointer first, and only return a string if it's valid. Otherwise, return nil. That's now part of win32-api 1.0.4, which I just released tonight.
BTW, the equivalent Perl code using Win32::API dumps core.