Lim Chin Hong
Lim Chin Hong

Reputation: 53

Regarding free function in c

May I know that if I free something in C programming language and I declare it as pointer before, it would just free out the memory but the pointer is still there or the pointer data type will also be destroyed as the code below. Also, may I know that if I want to free up my memory in this situation, why would I use free(list) in the end instead of using free(tmp)? Below is my code:

#include <stdio.h>
#include <stdlib.h>

int main(void){

    int *list = malloc(3 *sizeof(int));
    if (list==NULL){
        return 1;
    }

    list[0] = 1;
    list[1] = 2;
    list[2] = 3;

    int *tmp = malloc(4 * sizeof(int));
    if (tmp==NULL){
        free(list);
        return 1;
    }

    for (int i = 0; i < 3; i++){
        tmp[i] = list[i];
    }

    tmp[3] = 4;

    free(list);

    list = tmp;

    for (int i = 0; i < 4; i++){
        printf("%i\n", list[i]);
    }

    free(list);
}


Upvotes: 1

Views: 76

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

In these declarations

int *list = malloc(3 *sizeof(int));

int *tmp = malloc(4 * sizeof(int));

you declared two pointers list and tmp that has automatic storage duration. The pointers themselves point to dynamically allocated arrays that (the memory occupied by the arrays) should be freed using the function free to avoid memory leaks.

After calling the function free the pointers will have invalid values.

What the program is doing is at first it allocated dynamically an integer array with three elements and the address of the allocated memory is assigned to the pointer list.

int *list = malloc(3 *sizeof(int));

Then the program tries to reallocate the array by means at first of allocating dynamically a new array with four elements

int *tmp = malloc(4 * sizeof(int));

If the allocation was successful then the old array is freed

free(list);

and the address of the new array is assigned again to the pointer list.

list = tmp;

That is now the two pointers list and tmp point to the same dynamically allocated array. You can use either pointer to free the allocated memory but logically it is better to use the pointer list because the program simulates reallocation an array initially pointed to by the pointer list.

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49803

Calling free does not affect the pointer or its contents, just what the pointer pointed to. But the value in that pointer should no longer be considered valid.

The part about your specific use of free was addressed in the comments.

Upvotes: 4

Related Questions