Why do I have to use free() when I declare a pointer such as:
int *temp = (int*)malloc(sizeof(int))
*temp = 3;
but not when I do:
You don't always have to use free on a pointer, just ones declared with malloc. You can declare a pointer that points to a memory location on the stack
int a = 3;
int* p = &a;
and this memory (along with the pointer) will also be automatically disposed of when it goes out of scope. Using malloc allocates the same memory on the heap, so you have to handle cleanup manually.