为什么指向字符串文字后无法指针free()

Mic*_*chi 2 c

关于我的问题有一些相关的讨论,但没有关于我的问题的明确解释.

我认为free()无论我malloc()在哪里,无论何时何地,但我必须这样做,以防止内存泄漏.所以我有以下程序:

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    int *ptr;

    ptr = malloc(256);

    if (ptr == NULL)    {
        printf("Out of memory\n");
        return 1;
    }

    *ptr = 10;

    printf("The value of PTR is:\t%d\n",*ptr);
    free(ptr);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我有一个指针,我动态分配了一些内存(256),然后我检查了它的NULL字母free().

直到这里一切正常:指针被动态分配一些内存然后我free().

现在我将使用一个字符指针,在我将动态分配一些内存(256)后,我将指向字符串文字的指针,让我们说MICHI:

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    char *ptr;

    ptr = malloc(256);

    if (ptr == NULL)    {
        printf("Out of memory\n");
        return 1;
    }

    ptr = "michi";
    printf("%s",ptr);

    free(ptr);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在这里我做错了,因为如果我尝试free()它,那么它将无法工作,因为它发生了我将要释放一个非堆对象.

所以我迷失在这里,因为我认为malloc()你拥有的一切都是free()它.在指向字符串文字之后,究竟是什么使该指针不需要被free()编辑

ame*_*yCU 5

 ptr = malloc(256);
 ...
 ptr = "michi";
 printf("%s",ptr);
 free(ptr);
Run Code Online (Sandbox Code Playgroud)

当你分配内存ptr然后你指向它string literal.因此指针ptr不再指向由分配的内存malloc.

并且free内存不会被分配malloc或类似功能导致的错误程序.

这样做 - 而不是 -

 strcpy(ptr,"michi");
Run Code Online (Sandbox Code Playgroud)