On Thu, Jan 19, 2012 at 10:17:02AM -0800, Philip Guenther wrote: > On Thu, Jan 19, 2012 at 4:18 AM, Edd Barrett <[email protected]> wrote: > > I recently got caught out by scandir's quirky memory allocation. Should > > we add a note so that others don't have to go through this pain too? > > Could you elaborate on how this affected your code? I'm trying to > think of some way for code to depend on this that isn't undefined > behavior by the POSIX standard and (sorry) just a bad idea in > practice...
Well, if I want to make a copy of a directory entry, I can either memcpy() it or copy attribute by attribute, using strlcpy on the d_name. Memcpy() will segfault sporadically since I'm not told that dirent isn't fully allocated. The problem as I see it is that the man page states "builds an array of pointers to directory entries using malloc(3)". But the implementation behaves according to IEEE Std 1003.1-2008: "Entries for which the function referenced by sel returns non-zero shall be stored in strings allocated as if by a call to malloc()" I find "strings" a bit obscure, but at least it makes it somewhat clearer that one can not just memcpy() based on sizeof(dirent). While helping Edd debug his program, "strings" gave me enough of a hint to suspect how the implementation works. I would prefer something like: - "builds an array of pointers to nul terminated directory entries using malloc(3)" - "builds an array of pointers to variable-size directory entries using malloc(3)" - "builds an array of pointers to partially allocated directory entries using malloc(3)" however I'm not really happy with these...
