当我们在C中释放初始化的char指针时会发生什么?

时间:2019-07-28 15:47:16

标签: c

有人可以解释下面的代码吗,为什么即使释放了指针也为什么会产生“ h”作为输出?

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char *s = "hello";
    free(s);
    printf("%c", *(s));
    return 0;
}

1 个答案:

答案 0 :(得分:3)

除了free()(或malloc()calloc()以外的任何其他方式不能获得的内存,您都不能realloc()。 您调用UB,一切都会发生……包括您所期望的。

如果您的程序崩溃了(???),您会很高兴并且仍然一无所知。
很高兴您很幸运,因为意外的UB表现导致您提出问题。