在c中释放指向动态数组的指针 [英] free a pointer to dynamic array in c

查看:128
本文介绍了在c中释放指向动态数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用malloc在c中创建一个动态数组. 例如:

I create a dynamic array in c with malloc. e.g.:

myCharArray = (char *) malloc(16);

现在我是否要创建一个像这样的函数并将myCharArray传递给它:

now if I make a function like this and pass myCharArray to it:

reset(char * myCharArrayp)
{
    free(myCharArrayp);
}

这行得通吗,还是我将以某种方式仅释放指针的副本(myCharArrayp),而不释放实际的myCharArray?

will that work, or will I somehow only free the copy of the pointer (myCharArrayp) and not the actual myCharArray?

推荐答案

那样就可以了,并释放您所期望的内存.

That will be fine and free the memory as you expect.

我会考虑编写类似的函数

I'd consider writing a function like

 void reset(char** myPointer) {
     if (myPointer) {
         free(*myPointer);
         *myPointer = NULL;
     }
 }

以便在释放指针后将其设置为NULL.重用以前释放的指针是常见的错误来源.

So that the pointer is set to NULL after being freed. Reusing previously freed pointers is a common source of error.

这篇关于在c中释放指向动态数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆