const char* 应该在 C 中释放吗?

Lar*_*ara 2 c free constants function char

请考虑以下代码。我想问一下这是否正确,是否缺少什么。还有其他方法可以制作吗。

#include <stdio.h>
#include <string.h>
const char *getOrder (const char *day)
{
    if (strncmp(day, "Monday", 7) == 0) {
        return "first";
    } else if (strncmp(day, "Tuesday", 7) == 0) {
        return "second";
    } else if (strncmp(day, "Wednesday", 9) == 0) {
        return "third";
    } else if (strncmp(day, "Thursday", 8) == 0) {
        return "forth";
    } else if (strncmp(day, "Friday", 6) == 0) {
        return "fifth";
    } else if (strncmp(day, "Saturday", 8) == 0) {
        return "sixth";
    } else if (strncmp(day, "Sunday", 6) == 0) {
        return "seventh";
    } else
        return NULL;
}
int main()
{
    const char* str = NULL;
    str = getOrder ("Monday");
    printf("str : %s\n", str);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

小智 5

决定是否需要释放的不是变量的类型,而是它驻留在内存的哪一部分。

如果您使用malloc或相关函数分配内存,它将存在于堆上,因此您必须调用free它们。

在您的示例中,这些字符串是在静态内存中创建的(而不是像注释之一中所建议的那样从堆栈中创建,否则一旦函数返回您就无法使用它,因为它们将被覆盖)。

这些字符串被编译到运行时二进制文件本身中(您可以运行strings <your binary>并且您将看到它们。加载程序后,将为此类常量数据保留一个特殊的内存区域,因此您不需要释放它。

附带说明一下,您必须从右到左读取 C/C++ 类型,因此类型const char*意味着您有一个指向常量字符串的指针。这意味着您无法修改它指向的字符串,但它没有说明该指针后面的内存是如何分配的。它可能在堆上,在堆栈上,或者在静态内存上,只是类型不会告诉你。