CloudPotato
CloudPotato

Reputation: 1275

Correct usage of free()

I started to improve my basic C knowledge.

For that I tried to work with pointer data types.

I created a list like this:

typedef struct lsEle *listPointer;
typedef struct lsEle {int index; listPointer next; int value;} element;

with the global variable

listPointer header;

In my remove(int index) function I now want to remove the element from the list at the index.

void removeAtIndex(int index) {
    if (index < 0) {
        printf("You have to enter a index >= 0\n");
        return;
    } else {
        listPointer tmp = header;
        if (index == 0) {
            if (header->next == NULL) {
                header = NULL;
            } else {
                header = header->next;
            }
            free(tmp);
        } else {
            int counter = 0;
            while (1) {
                if (tmp->index == index - 1) {
                    break;
                }
                if (tmp->next != NULL) {
                    tmp = tmp->next;
                    counter++;
                } else {
                    break;
                }
            }
            if (index - 1 != counter) {
                printf("You have to enter a index <= %d\n", counter);
                return;
            } else {
                listPointer tmp_tmp = tmp->next;
                tmp->next = tmp_tmp->next;
                free(tmp_tmp);
            }
        }
        //Now update all index
        while (1) {
            if (tmp->next != NULL) {
                tmp = tmp->next;
                tmp->index = tmp->index - 1;
            } else {
                break;
            }
        }
    }
}

The code works fine.

My question is now: Do I use free() correctly? My goal was to remove the element "object" from the heap.

What happens when I do not use free? After the function exit from remove I don't have access to tmp_tmp any more, but does the "removed" object stay in memory?

Upvotes: 0

Views: 71

Answers (1)

Nikita
Nikita

Reputation: 6427

Do I use free() correctly?

You use free correctly if you previously allocate memory with malloc, calloc or realloc.

What happens when I do not use free?

Memory is not deallocated and you got memory leak.

After the function exit from remove I don't have access to tmp_tmp any more, but does the "removed" object stay in memory?

You deallocate memory pointed by tmp_tmp with free(tmp_tmp) so object removed from memory.

Upvotes: 1

Related Questions