Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何为局部变量释放动态分配的内存?_C - Fatal编程技术网

C 如何为局部变量释放动态分配的内存?

C 如何为局部变量释放动态分配的内存?,c,C,示例程序: #include <stdio.h> #include <malloc.h> void f(int n) { char *val = (char *) malloc(12*sizeof(char)); val = "feels...."; printf("%s", val); // free val; // if enable, compile time error: expected ';' before 'v

示例程序:

#include <stdio.h>
#include <malloc.h>

void f(int n) {
     char *val = (char *) malloc(12*sizeof(char));
     val = "feels....";

     printf("%s", val);

 //  free val;     // if enable, compile time error: expected ';' before 'val'   free val;   
 }

 int main()
 {
      f(1);

      return 0;
 }
#包括
#包括
空f(整数n){
char*val=(char*)malloc(12*sizeof(char));
val=“感觉……”;
printf(“%s”,val);
//free val;//如果启用,编译时错误:应为'val'之前的';'free val;
}
int main()
{
f(1);
返回0;
}

是否需要释放动态分配的内存?如果是,如何操作。

是,您需要释放内存。但是,当为字符串分配内存时,填充字符串的方法不是为其分配字符串,因为它会替换已分配的内存。相反,您应该像这样使用函数
strcpy

char *val = malloc(12*sizeof(char));
strcpy(val,"feels....");

printf("%s", val);
free(val);
与此相反:

 char *val = (char *) malloc(12*sizeof(char));
 val = "feels....";  // val points now to the string literal ""feels...."
                     // discarding the value returned by malloc
 ...
 free(val);          // attempt to free the string literal which will
                     // result in undefined behaviour (most likely a crash)
你可能想要这个:

 char *val = malloc(12*sizeof(char));  // in C you don't cast the return value of malloc
 strcpy(val, "feels....");  // the string "feels...." will be copied into
                            // the allocated buffer
 ...
 free(val);          // free memory returned previously by malloc

编译问题是因为
free
是一个函数,您需要将其参数放在括号中

free(val);
另一个问题是内存泄漏

C中的字符串实际上只是指向(希望是)包含
char
数据的内存块的指针。字符串的结尾由值为0的
char
表示。要记住的是,变量只是一个指针,就像其他指针一样。所以

 char *val = (char *) malloc(12*sizeof(char));
上面的行动态分配一个内存块,并将指向它的指针分配给
val

 val = "feels....";
上一行将指向字符串文字的指针指定给
val
以覆盖
val
中的上一个指针。它没有以任何方式触及第一行中
malloc
ed的内存块。此外,您丢失了对
malloc
ed块的所有引用,因此它已泄漏。没有办法免费使用它

字符串文字通常在编译时创建,它们占用的内存将是程序的一部分。这意味着它们不是从堆里来的(其中
malloc
从中获取其内存。这意味着,反过来,当您尝试
free
字符串文本时,坏事情就会发生。在现代体系结构中,程序文本在操作系统级别受到保护,因此尝试
free
部分内容几乎肯定会导致程序崩溃

只要您不想更改字符串的内容,就不需要为其添加
malloc
空格。您可以省略
malloc
行(以及相应的
free
),程序仍然可以运行

如果确实要更改字符串,获取字符串文本可变副本的最简单方法是使用
strdup

char *val = strdup("feels....");

// Do stuff with the string

free(val); // strdup strings need to be freed
strdup
是一个Posix函数,但不是C标准函数,因此您的平台可能没有它。不过,实现自己的函数非常简单

char* myStrDup(const char* thingToDup)
{
    char* ret = malloc(strlen(thingToDup) + 1); // strlen returns the length without the terminating nul. Hence add 1 to it to allocate
    strcpy(ret, thingToDup); // Copies the entire string including the terminating nul.
    return ret;
}
自由(val)
与显示的代码相反,您不能!您将指针重新分配到其他位置,当您将指针传递到函数时,会导致泄漏和未定义的行为。如果您希望分配的内存包含字符串,则必须包含字符串。请记住,字符串需要额外的字符作为终止符,因此字符串为12个字符ters需要13的空间。此外,
是一个过时的头文件,您应该为
malloc
free
函数包含