Reputation: 4878
If you were to do something like:
char array[2][5] = {"cars", "tags"}
char array2[] = "computer";
There has been an implicit allocation of memory allocated equal to(for the first line):
sizeof(array); OR
sizeof(char*10);
Or however you want to do it.
Alternatively, one could do this:
char *ptr = "cars";
char *ptr2 = malloc(sizeof(*ptr2)*5);
*ptr2 = "cars";
I know that if you are using pointers to explicitely allocate memory using malloc then it is good practice to free that pointer using free(ptr);
However, when you define things as above, are the following calls necessary on the same grounds as the explicit allocation of memory?
free(ptr);
free(ptr2);
free(array);
free(array2);
-- As an aside, all of the above delcarations/initializations are implicitely NULL-terminated strings, right?
Upvotes: 2
Views: 236
Reputation: 36
You only have to free memory yo have allocated using malloc, when you declare a static array memory is freed automatically at the end of the code block.
Upvotes: 1
Reputation: 225172
*ptr2 = "cars";
is not a valid statement. If you want to point ptr2
someplace else, you need to use:
ptr2 = "cars";
If you want to overwrite the memory ptr2
points to, use strcpy
:
strcpy(ptr2, "cars");
Only ptr2
needs to be freed - it's the only one you allocated with malloc
. Note that if you make the ptr2 = "cars"
assignment mentioned above, you won't be able to free the original memory you allocated. That's a logical error known as a "memory leak".
Upvotes: 1
Reputation: 3107
However, when you define things as above, are the following calls necessary on the same grounds as the explicit allocation of memory?
No, its illegal to free memory which are not returned by malloc
or calloc
or realloc
.
all of the above delcarations/initializations are implicitely NULL-terminated strings, right?
Yes, those strings are called string literals and will be NULL termintaed.
Upvotes: 1
Reputation: 613461
You should only ever call free
when passing something allocated with a call to malloc
. Which means that you should only ever call free
with ptr2
.
Furthermore, your assignment *ptr2 = "cars"
is a syntax error. You would need to use strcpy
to fill ptr2
. Like this:
char *ptr2 = malloc(sizeof(*ptr2)*5);
strcpy(ptr2, "cars");
C strings are null-terminated by convention, and string literals, i.e. "cars"
are null-terminated.
Upvotes: 1
Reputation: 158599
You only need to free
memory allocated with malloc
, the other cases you specified are pointers to string literals or automatic variables(usually allocated on the stack) attempting to free them is undefined behavior.
C style strings are NULL
terminated.
Also, important to note that:
*ptr2 = "cars";
is not correct syntax.
Upvotes: 2