This archive contains answers to questions sent to Unidata support through mid-2025. Note that the archive is no longer being updated. We provide the archive for reference; many of the answers presented here remain technically correct, even if somewhat outdated. For the most up-to-date information on the use of NSF Unidata software and data services, please consult the Software Documentation first.
Hi Sean, Thanks for looking at the problem and providing your comments. I will use strlcat() instead, which I will provide a version of if it's not available on the target platform. > This is buggy too. The first time through the while loop 'sp' points to > 'newlen' bytes of memory. Assume 'repls[j]' is a very long string. The > strncat() will fill 'sp' and leave it unterminated. So 'newlen-1' would > be better. But that's still no good because you advance the 'sp' > pointer, so each time through the loop you should be passing a smaller > and smaller length to strncat(). I suppose there is no real danger > since you compute newlen correctly in the first place, but still, if > you're not passing the correct length to strncat(), you may as well just > use strcat. :) I have to disagree with this analysis, but I didn't provide the context in which the code fragment was embedded, so I can understand why you concluded their may be a bug. First, repls[j] is always a short string of known length lens[j], as these two arrays are precomputed on initialization in a table of replacement strings and their lengths (for some special characters that might appear in names). Thus strncat() cannot fill sp and leave it unterminated, as the value of newlen is explicitly computed to include the lengths of all replacement strings + 1 for the null termination. Also sp is advanced in the loop by exactly the same value that newlen is decremented by sp += lens[j]; newlen -= lens[j]; so a smaller and smaller value of newlen is passed to strncat() for each iteration. Of course that's irrelevant to this strncat() call, because it aborted on the first time through the loop, when sp pointed to a null byte at the beginning of an allocated buffer for a string. Also changing the strncat(...,newlen) to strncat(...,newlen-1) led to the same abort on the first time through the loop. But I appreciate the suggestion to use strlcat() and will make that change this afternoon. Unfortunately, -D_FORTIFY_SOURCE=2 doesn't seem to check strlcat() calls, so I'd better get it right! Thanks again, --Russ Russ Rew UCAR Unidata Program address@hidden http://www.unidata.ucar.edu Ticket Details =================== Ticket ID: PUM-976132 Department: Support netCDF Priority: Normal Status: Closed