从 POSIX 函数返回指针的一般内存所有权规则是什么?

What's general memory ownership rules for returning pointers from POSIX functions?

今天我试图调用 strerror POSIX 函数。它returns一个char*,现在我不确定要不要freefree

The application shall not modify the string returned.

我认为返回指针应该是指向内部静态缓冲区的指针,在那种情况下,我永远不应该碰它。但是,它只是说 "do not modify",根本没有谈论内存所有权。我很困惑。我会假设 "no touch" 为 "system owns, caller borrows",但我仍然没有信心,因为这只是我的推断,而不是承诺或定义。

我对C/POSIX编程不是很熟悉。我认为这一定有一个完善的约定或明确的规则,但我找不到。

C/POSIX 函数的内存所有权规则是什么?

惯例是您不会释放指针(或写入指针),除非返回它的函数的描述告诉您应该释放它。但是,POSIX 表达那个的成语有点奇怪,所以很容易混淆。

例如,strdup and strndup 是:

The returned pointer can be passed to free(). […] duplicating the provided s in a new block of memory allocated as if by using malloc()

对于realpath,是这样的:

If resolved_name is a null pointer, the generated pathname shall be stored as a null-terminated string in a buffer allocated as if by a call to malloc().

将此与 getaddrinfo or fopen, which does not use such language. Instead you are expected to use the specific deallocation functions (freeadrinfo and fclose) 的文档进行对比。

简而言之,每次 POSIX 表示 可以将指针传递给 free 指向分配为内存的指针如果使用 malloc(),这实际上意味着如果要避免内存泄漏,则需要释放该指针。否则不允许释放指针。