gpt4 book ai didi

c - 我应该在 C 中的 basename/dirname 之后释放 strdup 指针吗?

转载 作者:太空狗 更新时间:2023-10-29 15:32:39 25 4
gpt4 key购买 nike

我想使用 POSIX 的 basename 函数(而不是 GNU 的)。

来自手册页:

Both dirname() and basename() may modify the contents of path, so it may be desirable to pass a copy when calling one of these functions.

These functions may return pointers to statically allocated memory which may be overwritten by subsequent calls. Alternatively, they may return a pointer to some part of path, so that the string referred to by path should not be modified or freed until the pointer returned by the function is no longer required.

它还说:

RETURN VALUE
Both dirname() and basename() return pointers to null-terminated strings. (Do not pass these pointers to free(3).)

所以这个例子表明:

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);

strdup(strndup) 手册页说:

Memory for the new string is obtained with malloc(3), and can be freed with free(3).

所以问题是:我应该释放 dirc 和 basec(根据 strdup)还是不释放(根据 basename)?

最佳答案

dnamebname 可能分别使用了 dircbasec 的一部分,所以释放是不安全的dircbasec

我会对 dirnamebasename 调用的结果执行 strdup。然后释放dircbasec 是安全的,你知道你必须释放你的拷贝。

(是的,它很乱,但我认为这比记住你还不能释放 dirc 因为 dname 可能会或可能不会使用它要干净...)

关于c - 我应该在 C 中的 basename/dirname 之后释放 strdup 指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26111096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com