I have read this post about check before calling free(). I want to further confirm through a case.
The following codes are copied from my C++ project (tested, no error/warning). I just want to confirm the right way to check memory allocation and free() in C++.
// 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)
}
Questions:
In part 3, is this the correct way to check if(!params). Any error is not considered here?
In part 6, I give 2 options - if(params) and if(params!=NULL). Are they same?
In part 1, struct includes pointer(p1) and non-pointer(p2). What is the difference between free a pointer, free a non-pointer, and free a combination of both?
If I use delete[ ] instead of free(). How? and what's the difference?