In my opinion, that would be unlikely, since it sometimes works, and sometimes not, and I guess the output file is always being written in the same place, no ?
"premature end of script headers" happens when the cgi-bin script crashes before it has even started to send back a response to the browser.
So I guess your best option would be to add some logging into your script, and try to figure out when it crashes and for what reason.
Whatever your cgi-bin script prints to STDERR will usually find its way into the Apache error log for that server.