Please consider the following code. I am asking if this is correct, is there something missing. Is there any other way to make it.
#include <stdio.h>
#include <string.h>
const char *getOrder (const char *day)
{
if (strncmp(day, "Monday", 7) == 0) {
return "first";
} else if (strncmp(day, "Tuesday", 7) == 0) {
return "second";
} else if (strncmp(day, "Wednesday", 9) == 0) {
return "third";
} else if (strncmp(day, "Thursday", 8) == 0) {
return "forth";
} else if (strncmp(day, "Friday", 6) == 0) {
return "fifth";
} else if (strncmp(day, "Saturday", 8) == 0) {
return "sixth";
} else if (strncmp(day, "Sunday", 6) == 0) {
return "seventh";
} else
return NULL;
}
int main()
{
const char* str = NULL;
str = getOrder ("Monday");
printf("str : %s\n", str);
return 0;
}
CodePudding user response:
What will determine if you have to free or not is not the type of the variable, but on which part of memory it resides.
If you allocate memory using malloc
or a related function, it will live on the heap, thus you have to call free
on them.
In your example, these strings are created in static memory (not from the stack as suggested in one of the comments, otherwise you could not use it once the function returns, as they would have been overwritten).
These strings are compiled into the run-time binary itself (you can run strings <your binary>
and you will see them. Once the program is loaded, a special area of the memory is reserved for such constant data, thus you don't need to free it.
As a side note, you have to read the C/C types from right-to-left, so
type const char*
means is that you have a pointer to a constant string. That means that you cannot modify the string pointed by it, but it does not say anything about how the memory behind this pointer was allocated. It could be on the heap, on the stack, or on static memory, just the type will not tell you.
CodePudding user response:
The conclusion is NO.
The reason is free() should be used as the partner of malloc(), calloc() or realloc(). Or to say only a pointer is returned by those alloc function, could it be recycled by free().
And an addtional reason is all those strings you write in your code is allocated in section .rodata, that means those strings are loaded in a memory space you cannot edit but only read, so even there is a method to free them, you still cannot util the memory space.