tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: dirname(3) used on its own results?



Robert Elz wrote:

> What it is going to say (approved update for next revision) is ...
>
> 	The dirname() function may modify the string pointed to by path, and may
> 	return a pointer into the input string. The returned pointer might be invalidated
> 	if the input string is subsequently modified or freed. If path does not contain a
 '/', 
> 	is a null pointer, or points to an empty string the returned pointer may point to
> 	constant data that cannot be modified.
>
> That is, it is now expected, not just allowed, to modify its input and return 
> a pointed to some part of the original input.   That allowws thread safety.   
> But sometimes that cannot be done (the input is not lonng enough to contain
> the required result) when that happens, a const char * result (which obviously
> cannot be modified) can be returned (this allows return "." and return "/" in
> appropriate cases).   Since the result might be a string that cannot be 
> modifried, and the input is expected to be modified, calling dirname() with the
> result of a previous dirname() is never safe.
>
> In general, unless the result from dirname() is to be used and forgotten 
> immediately (eg: used in a printf, or an sprintf to generate a different 
> filename) it should always be strdup'd - what's more, the input should
> usually be a copy of the actual string.

The code in question is essentially:

	dir_buf = strdup(path);
	dir = dirname(dir_buf);
	while (not_seen(dir)) {
		save(dir);
		dir = dirname(dir);
	}

with a little extra error checking.  Even with the new approved wording
for the next revision of the spec for dirname(3) you quoted I'm still not
sure if the code above should be considered valid or not.

Cheers,
Simon.


Home | Main Index | Thread Index | Old Index