Thursday, March 22, 2018

c - freeing allocated memory



gcc 4.4.5 c89



I have a function called create_object where I allocate memory for a global structure. And I have a function called destroy_object where I check that the pointer is not null, then I free. Just incase I free memory that hasn't been allocated. However, I have tested this by making 2 consecutive calls to destroy_object. However, I get a stack dump on the second call. However, I am sure that it would not free as I have assigned the pointer to NULL. So it should skip the free function.



static struct Config_t {

char protocol[LINE_SIZE];
char mode[LINE_SIZE];
} *app_cfg = NULL;

int create_object()
{
app_cfg = malloc(sizeof *app_cfg);
memset(app_cfg, 0, sizeof *app_cfg);
}


void destroy_config()
{
/* Check to see if the memory is ok to free */
if(app_cfg != NULL) {
free(app_cfg);
app_cfg = NULL;
}
}



Many thanks for any suggestions,



================= EDIT ==========
Basicially I have in my main function a call to create_object() and I do some processing and then make a call to destory_object.



int main(void)
{
create_object();

/* Do some processing on the structure */


destroy_object();

return 0;
}


========================= Final Edit ====
static struct Config_t {
char protocol[LINE_SIZE];

char mode[LINE_SIZE];
} app_cfg[1] {{"", ""}};



And now I am not using malloc and free.


Answer



I have only one suggestion. Don't allocate memory for this, it's a waste of effort.



Since app_cfg is a file-level variable, you can only have one copy at a time anyway, so there's little point in allocating and de-allocating it.



Just create it as a static non-pointer and use it:




static struct Config_t {
char protocol[LINE_SIZE];
char mode[LINE_SIZE];
} app_cfg;


You can still provide a create and destroy which memset the structure to zeros but even that may not be required:



void create_object (void) {

memset(&app_cfg, 0, sizeof(app_cfg));
}

void destroy_config (void) {
memset(&app_cfg, 0, sizeof(app_cfg));
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...