在调用free()之前,我已阅读this有关检查的文章。我想通过一个案例进一步确认。
以下代码是从我的C++项目复制的(经过测试,没有错误/警告)。我只想确认检查 C++ 中的内存分配和 free()的正确方法。
// part 1: declare
typedef struct cipher_params_t {
unsigned char * p1;
int p2;
}cipher_params_t;
// part 2: allocate memory
cipher_params_t *params = (cipher_params_t*)malloc(sizeof(cipher_params_t));
// part 3: check allocate memory
if (!params) {
/* Unable to allocate memory on heap*/
fprintf(stderr, "ERROR: malloc error: %s\n", strerror(errno));
return errno;
}
// part 4: assign values
unsigned char key[16] = {0x01, 0x02, ..., 0x0f};
params -> p1 = key;
params -> p2 = 1;
// part 5: use params for some function
some_func(params);
// part 6: free params lastly
cleanup1(params);
// cleanup2(params); //another option
void cleanup1 (cipher_params_t *params){
if(params) free(params)
}
void cleanup2 (cipher_params_t *params){
if(params!=NULL) free(params)
}
问题:
最佳答案
是的,这是正确的,因为malloc()
失败时返回NULL。
是的,它们是相同的。但是在C++中,有很多原因使用nullptr
(适当的类型nullptr_t
)而不是NULL。
实际上,您不也不能释放非指针。在您的情况下,您只释放了一个指向cipher_params_t
结构的指针。
使用malloc()
,您可以为包含cipher_params_t
的内容分配内存,而只需为其分配足够的空间即可。当free()
时,无论结构包含什么内容,都释放分配的内存。
请注意,malloc()
和free()
既不针对指向的结构也不对其内容调用构造函数/析构函数。它们只是保留/分配内存空间。
永远不要将malloc()
/free()
,new
/delete
和new[]
/delete[]
混合使用,因为它们不会做相同的事情。您应该阅读What is the difference between new/delete and malloc/free?以获取更多信息。