C中的自由未初始化指针

Free uninitiailized pointer in C

如果我为一个指针动态分配了一个space,列出这个:

int *a = (int*)malloc(sizeof(int));

我应该在代码完成后释放 a 吗?谢谢!

是的。 如果你成功地 malloc 一些东西也是正确的释放它。

int *a = (int *) malloc(sizeof int);
if (a != NULL)
{
    /* Do whatever you need to do with a */
    free(a);
}
else
{
    puts("the malloc function failed to allocate an int");
}
int *a = malloc(sizeof(*a));
if (a) 
{
    /* a is now valid; use it: */
    *a = 1 + 2 + 3;
    printf("The value calculated is %d\n", *a);
}

/* Variable A is done being used; free the memory. */
free(a);  /* If a failed to be allocated, it is NULL, and this call is safe. */

我觉得你对指针有点误解。

您的标题是:

Free uninitialized pointer ...

你的密码是

int *a = (int*)malloc(sizeof(int));

问题在于代码中没有未初始化的指针。代码中唯一的指针是变量 a,它 是由 malloc.

返回的值初始化的

释放未初始化的指针是不好的 - 示例:

int *a;  // a is an uninitialized pointer

free(a);  // Real bad - don't do this

但是因为你实际上初始化了指针 - 是的,当你使用 object/memory 指针 a 指向的完成时,你必须调用 free 。 pointed-to object(又名内存)是否被赋值并不重要。

一般规则:对于 malloc 的每次调用都必须调用 free

(例外:如果您的程序终止,您不需要调用 free

int *a = (int*)malloc(sizeof(int));

should I free a when the code is done?

问题应该是

Must I free a when the code is done?

答案是肯定的。 malloc 必须附有 free 语句。

free(a);