你将如何释放分配的内存?
How will you free the memory allocated?
我需要释放一些在我的程序上分配的内存。我可以在需要时使用一些东西来清理内存吗?
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main()
{
int **p, i, j;
p = (int **) malloc(MAXROW * sizeof(int*));
return 0;
}
点 1
您无法释放一些内存。你必须释放 all。详细地说,无论 单个 调用 malloc()
或家庭分配的内存,一次都是 free
-d。您不能释放 一半(左右)分配的内存。
点 2
- 请do not cast
malloc()
和C
中的家人return值。
- 你应该 always write
sizeof(*ptr)
而不是 sizeof(type*)
.
点 3
您可以使用 free()
释放分配的内存。
例如,参见下面的代码,请注意内联注释。
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main(void) //notice the signature of main
{
int **p = NULL; //always initialize local variables
int i = 0, j = 0;
p = malloc(MAXROW * sizeof(*p)); // do not cast and use sizeof(*p)
if (p) //continue only if malloc is a success
{
//do something
//do something more
free(p); //-----------> freeing the memory here.
}
return 0;
}
很简单。
您可以使用此代码来清理您唯一使用的变量。
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main()
{
int **p, i, j;
p = (int **) malloc(MAXROW * sizeof(int*));
free(p);
return 0;
}
我需要释放一些在我的程序上分配的内存。我可以在需要时使用一些东西来清理内存吗?
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main()
{
int **p, i, j;
p = (int **) malloc(MAXROW * sizeof(int*));
return 0;
}
点 1
您无法释放一些内存。你必须释放 all。详细地说,无论 单个 调用 malloc()
或家庭分配的内存,一次都是 free
-d。您不能释放 一半(左右)分配的内存。
点 2
- 请do not cast
malloc()
和C
中的家人return值。 - 你应该 always write
sizeof(*ptr)
而不是sizeof(type*)
.
点 3
您可以使用 free()
释放分配的内存。
例如,参见下面的代码,请注意内联注释。
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main(void) //notice the signature of main
{
int **p = NULL; //always initialize local variables
int i = 0, j = 0;
p = malloc(MAXROW * sizeof(*p)); // do not cast and use sizeof(*p)
if (p) //continue only if malloc is a success
{
//do something
//do something more
free(p); //-----------> freeing the memory here.
}
return 0;
}
很简单。 您可以使用此代码来清理您唯一使用的变量。
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main()
{
int **p, i, j;
p = (int **) malloc(MAXROW * sizeof(int*));
free(p);
return 0;
}