我用 malloc 在 C 中创建一个动态数组,即:
myCharArray = (char *) malloc(16);
现在,如果我创建一个这样的函数并通过myCharArray
to it:
reset(char * myCharArrayp)
{
free(myCharArrayp);
}
这会起作用,还是我会以某种方式只释放指针的副本myCharArrayp
而不是实际的myCharArray
?
您需要了解指针只是一个变量,它存储在堆栈中。它指向一个内存区域,在本例中是在堆上分配的。您的代码正确释放堆上的内存。当您从函数返回时,指针变量就像任何其他变量(例如int
),被释放。
void myFunction()
{
char *myPointer; // <- the function's stack frame is set up with space for...
int myOtherVariable; // <- ... these two variables
myPointer = malloc(123); // <- some memory is allocated on the heap and your pointer points to it
free(myPointer); // <- the memory on the heap is deallocated
} // <- the two local variables myPointer and myOtherVariable are freed as the function returns.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)