Should I free the strdup pointer after basename / dirname in C?
I want to use a POSIX feature basename
(as opposed to GNU).
From the man page:
Both dirname () and basename () can change the contents of the path, so it might be desirable to pass a copy when calling one of these functions.
These functions can return pointers to statically allocated memory, which can be overwritten by subsequent calls. On the other hand, they can return a pointer to some part of the path , so that the string specified in the path should not be modified or freed until the pointer returned by the function is no longer required.
It also says:
RETURN VALUE
Both dirname () and basename () return pointers to null terminated strings. ( Do not omit these pointers to free (3).)
So the example suggests something like:
EXAMPLE
char *dirc, *basec, *bname, *dname; char *path = "/etc/passwd"; dirc = strdup(path); basec = strdup(path); dname = dirname(dirc); bname = basename(basec); printf("dirname=%s, basename=%s\n", dname, bname);
The man page strdup
( strndup
) says:
The memory for the newline is obtained with malloc (3) and can be freed with free (3).
So the question is: should I free dirc and basec (according to strdup
) or not (according to basename
)?
source to share
dname
and bname
parts can be used dirc
and basec
respectively, so it is not safe to release them.
I would follow strdup
from the call results dirname
and basename
. It is safe to release dirc
both then basec
, and you KNOW that you need to release your copies.
(yes it is dirty, but I think it is cleaner than remembering that you cannot free dirc
, but since you dname
may or may not use it ...)
source to share