[英]Free allocated pointer passed to a function?
When shall I free my unsigned char* if I need to pass the unsigned char* into a function? 如果需要将未签名的char *传递给函数,什么时候应该释放我的未签名的char *? Example
例
void myFunction(unsigned char *request){
// do I need to use free(request); here?
}
int main (){
// main code
unsigned char *request = NULL;
// read from buffer and reallocate memory (using realloc & memcpy)
myFunction(request); // I do not want to read or use "request" after this function call.
free(request); // is this ok? Or should this be inside myFunction also?
return 0;
}
Use free()
on something as soon as you're done using it. 完成使用后,立即对某物使用
free()
。 So for instance, you probably wouldn't do it inside myFunction()
because you're probably still going to be interested in the value pointed at by request
when you exit that function back to main
. 因此,例如,您可能不会在
myFunction()
执行此操作,因为当您将该函数返回给main
时,您可能仍然会对request
指向的值感兴趣。
Usually you have to free it where you have allocated it, and don't need more it. 通常,您必须在分配它的位置释放它,而不需要更多它。 In This case you can do it in both places, but also, after freed set it to NULL, and next time when you'll try to free it, check for null
在这种情况下,您可以在两个地方都可以执行此操作,也可以在释放后将其设置为NULL,并且下次尝试释放它时,请检查是否为null
also you mai implement something like: 你也可以实现类似的东西:
void FreeAndNull(void *request){
if request <> NULL then
{ free(request); request = NULL; }
}
You don't have to do this - but a good practice is to free things at the same level as you allocated them. 您不必执行此操作-但一个好的做法是在分配内容的同时释放它们。 Eg don't allocate something in a function and free it after it is returned.
例如,不要在函数中分配某些东西并在返回后释放它。 Because then the lifecycle of the memory is not clear to you months later when you look at the code again.
因为那样,几个月后再次查看代码时,内存的生命周期就变得不清楚。
So it is much better to: 因此,执行以下操作要好得多:
request = malloc();
doStuff( request );
free( request );
than the pattern you have. 比你所拥有的模式。 C++ helps you with this pattern by creating constructors and destructors.
C ++通过创建构造函数和析构函数来帮助您使用此模式。 That is a constructor may actually allocate memory and essentially return it to you in the form of an object, but the compiler will automatically call the destructor for you freeing the memory.
也就是说,构造函数实际上可能会分配内存,并实质上以对象的形式将其返回给您,但是编译器会为您释放内存而自动调用析构函数。
So you can achieve something like the pattern you want with a much safer and more maintainable pattern if you wrap that request buffer in a class: 因此,如果将请求缓冲区包装在类中,则可以使用更安全,更可维护的模式来实现所需的模式,例如:
Request::Request() { mRequest = malloc(); }
Request::~Request() { if ( mRequest ) free( mRequest ); mRequest = NULL; }
...
{
Request request;
myFunction( request );
}
With this pattern you memory is cleaned up automatically. 使用此模式,您的内存将自动清除。 Safer and more maintainable.
更安全,更易维护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.