In these two declarations
char *str1 = "MyString1";
char str2[] = "MyString2";
you declared explicitly only one character array str2
. This array has automatic storage duration and the memory it occupies will be freed after exiting the function where it is declared. That is after exiting the function the array will not be alive and the memory it occupies can be reused by other objects.
You have to call the function free when an array was allocated using memory allocation functions as malloc
or calloc
.
In the first declaration you declared a pointer to the first character of the string literal "MyString1"
. The string literal is internally stored as a character array defined like
char unnamed_string_literal[] = { 'M', 'y', 'S', 't', 'r', 'i', 'n', 'g', '1', '\0' };
It has static storage duration and will be alive after exiting the function.
On the other hand the pointer itself has automatic storage duration and after exiting the function the memory occupied by it can be reused.