I was watching a lesson on malloc and while they were doing a specific example, it made no sense for why such code to print out the entire pointer.
#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)
return 1;
for (int i = 0; i < 3; i++)
tmp[i] = list[i];
tmp[3] = 4;
free(list);
//From this line and below is the thing in question.
list = tmp;
for (int i = 0; i < 4; i++)
printf("%i\n", list[i]);
}
OUTPUT:
~/test/ $ ./malloc_test
1
2
3
4
From my understanding of free(), it de-allocates the memory allocated by allocation functions and free() will 'free' up the memory of the pointer.
If I were to go by this definition:
*listwas allocated 12 bytes(3 * sizeof(int),sizeof(int) = 4- Hard code
listwith numbers *tmpwas allocated 16 bytes- Copy the numbers in
listtotmp - Free up list making it have no allocated bytes
- List is now equal to tmp
How can
listnow be equal totmpwhenlistdoesn't have any allocated memory?Is
listpointing to the address oftmp? If yes, why do we need to not allocate memory forlistsince earlier in the code, we did thisint *tmp = malloc(4 * sizeof(int));