第二行是“可怕的”错误:
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)
你将变量c分配两次,所以很明显,第一个赋值没有意义.
这就像写作:
int i = 5;
i = 6;
最重要的是,您“丢失”了已分配内存的地址,因此您将无法在以后发布它.
您可以按如下方式更改此功能:
char* m()
{
const char* s = "hello";
char* c = (char*)malloc(strlen(s)+1);
strcpy(c,s);
return c;
}
请记住,无论谁调用char * p = m(),都必须稍后调用free(p)…