Consider a (hopefully) simpler example of what Salem & Elysia have pointed out:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *array;
char my_string[] = "You just lost your malloced memory!";
/* Get some memory allocated for "array" */
array = malloc(128 * sizeof(*array));
if (array == NULL) {
fprintf(stderr, "%s", "malloc: Could not allocate memory.");
exit(EXIT_FAILURE);
}
/* We got the memory, so now we can use it as was intended.
* Note that the only way to use it is by the pointer
*/
strcpy(array, "My name is George.");
puts(array);
/* As you can see, the pointer stored in array is important, for without it,
* there would be no means to access the allocated memory. Now consider what
* happens when we make array point to something else:
*/
array = my_string;
puts(array);
/* How do we go back now, and work on the memory allocated previously? There is no longer
* a way to do it. This is especially troublesome, as now we cannot call free() to release
* the allocated memory. It is just hanging around, doing nothing.
*/
return 0;
}
Note also, how I called malloc (in red); It is a good practice to call malloc in this manner. You can read why here. You could also have a look at the following entries from the C-FAQ: