The second line is "horribly" wrong:
char* c = (char*)malloc(6*sizeof(char));
// 'c' is set to point to a piece of allocated memory (typically located in the heap)
c = "hello";
// 'c' is set to point to a constant string (typically located in the code-section or in the data-section)
You are assigning variable c
twice, so obviously, the first assignment has no meaning.
It's like writing:
int i = 5;
i = 6;
On top of that, you "lose" the address of the allocated memory, so you will not be able to release it later.
You can change this function as follows:
char* m()
{
const char* s = "hello";
char* c = (char*)malloc(strlen(s)+1);
strcpy(c,s);
return c;
}
Keep in mind that whoever calls char* p = m()
, will also have to call free(p)
at some later point...