C语言 关于free函数的问题


   
  #include <stdio.h>
  
#include <stdlib.h>
#include <string.h>
#define N 10

int main(void)
{
char src[N];
scanf("%s", src);
int len = strlen(src);
char* dest = (char *)malloc(sizeof(char) * len);
char* s = &src[len - 1];
char* d = dest;
while (len-- != 0)
*d++ = *s--;
printf("%s\n", dest);
dest = NULL; // 这里为什么不用free(dest)? 这样做的效果是否和free(dest)等同?
return 0;
}



相关链接

c 存储

Chicara 9 years, 6 months ago

malloc 之后必须要 free。至于将指针置为 NULL 可以做也可以不做,不过是个好习惯。

傀儡的诱惑 answered 9 years, 6 months ago

dest=NULL是把指针变量本身的地址类型的值给覆盖,原本所指向的变量所占的内存不会被释放,在c里面,用malloc申请的堆内存块,必须要用free显示释放。

别╰╮发骚 answered 9 years, 6 months ago

我觉得这段代码会产生内存溢出的问题,用malloc分配的内存必然需要free掉,然后再令dest=NULL。

XXX阿鬼 answered 9 years, 6 months ago

题主确定这是正确的代码吗?根据我学到的知识,用malloc申请的堆内存块,必须要用free显示释放。

漂浮的大饼 answered 9 years, 6 months ago

这不是显然不对的吗,c语言又不存在自动内存管理的问题,没有使用用malloc申请的内存空间没有使用free函数释放的话,是会一直被保留的。

本须和水鱼 answered 9 years, 6 months ago

Your Answer