Guilherme Cintra
Guilherme Cintra

Reputation: 81

Ideally shouldnt this code free tmp before ending?

Im confused on why is this code freeing list but not tmp after setting list to point to where tmp points (list = tmp;)

// Implements a list of numbers with an array of dynamic size

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

int main(void)
{
    // List of size 3
    int *list = malloc(3 * sizeof(int));
    if (list == NULL)
    {
        return 1;
    }

    // Initialize list of size 3 with numbers
    *list = 1;
    *(list + 1) = 2;
    *(list + 2) = 3;

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

    // Copy list of size 3 into list of size 4
    for (int i = 0; i < 3; i++)
    {
        tmp[i] = list[i];
    }

    // Add number to list of size 4
    tmp[3] = 4;

    // Free list of size 3
    free(list);

    // Remember list of size 4
    list = tmp;

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

    // Free list
    free(list);
    return 0;
}

Upvotes: 1

Views: 87

Answers (1)

Lundin
Lundin

Reputation: 214770

The only thing that matters is that you call free with the same address as you once got handed by malloc. The memory allocated is associated with that address, not with a pointer variable name.

  • At the first free(list); you free the first chunk allocated with int *list = malloc(3 * sizeof(int));.
  • list = tmp; Now both list and tmp point at the same location, the address returned from this malloc call: int *tmp = malloc(4 * sizeof(int));
  • From there we could either do free(list) or free(tmp), it doesn't matter since they point at the same location and it's the original address returned from the malloc(4 ... call.
  • After the second free() both list and tmp are "dangling pointers", they point at a memory region which is no longer available. Therefore it is often good practice to set the pointer(s) to NULL directly after calling free.

Upvotes: 1

Related Questions