korhan
korhan

Reputation: 301

Allocating recently freed memory

I have a struct that I use to build a linked list as below;

struct my_struct{
    char a[16];
    struct my_struct *next;
}

I free that linked list by below function;

void free_my_list(struct my_struct* recv) {

     if (recv->next != NULL)
         free_my_list(recv->next);

     free(recv);
     recv = NULL;
}

In my program, I use a struct _my_list over and over but free and malloc it every time as below:

struct my_struct *_my_list;

free_my_list(_my_list);
_my_list = (my_list *) malloc(sizeof(my_list));
_my_list->next = NULL;

Every time I fill the list, I print char arrays and then reset _my_struct by above code. Above code works fine on Ubuntu pc, but on Cent OS after printing first list(after first malloc _my_struct) correctly, following list are printed as corrupted data.

When I don't free and malloc memory during whole program execution it works fine in Cent OS too but I should reset list _my_list between printf() calls.

_my_list is filled and printed via below functions;

/*prints every item in my_list*/
void print_my_list(struct my_struct *recv, FILE *fd) {

   my_list *tmp;
   tmp = recv;

   while (tmp != NULL) {
       if (fwrite(tmp->a, 1, strlen(tmp->a), fd) == -1) {
               pritnf("error\n");
        }
       tmp = tmp->next;
   }
}

/*Add 'a' string to _my_list*/
void add_recv_to_list(struct my_struct **recv_list, char *recv) {

struct my_struct *tmp;
tmp = *recv_list;

if (*recv_list == NULL) {
    *recv_list = (struct my_struct *) malloc(sizeof(struct my_struct));
    tmp = *recv_list;

} else {

    while ((tmp->next) != NULL) {
        tmp = tmp->next;
    }
    tmp->next = (struct my_struct *) malloc(sizeof(struct my_struct));
    tmp = tmp->next;

}
strncpy(tmp->a, recv, MAX_NAME_LEN);
tmp->next = NULL;
}

What can be the reason, any ideas?

Upvotes: 1

Views: 135

Answers (1)

Slubb
Slubb

Reputation: 515

I think that your problem may start here:

struct my_struct *_my_list;

free_my_list(_my_list);
_my_list = (my_list *) malloc(sizeof(my_list));
_my_list->next = NULL;

When you initialize the struc: struct my_struct *_my_list; you don't assign it any value, so it holds whatever garbage data was in memory beforehand. When you free() that in free_my_list, the behavior is undefined (you are freeing something that you never malloc()ed - so the result may very well be corruption of something or other later on. Try changing your declaration to: struct my_struct *_my_list = NULL; (always a good practice to initialize pointers to NULL, anyway) and changing your free_my_list function to:

void free_my_list(struct my_struct* recv) {
    if (recv == NULL)
         return;

     if (recv->next != NULL)
         free_my_list(recv->next);

     free(recv);
     recv = NULL;
}

Upvotes: 1

Related Questions