我这里有一个noob问题,无法理解这里的错误.我在这里有以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Run Code Online (Sandbox Code Playgroud)
void copyFrom(char * mStr, char * str);
Run Code Online (Sandbox Code Playgroud)
int main() {
char * srcStr = "Robert bought a good ford car";
char * dstStr = NULL;
copyFrom(srcStr, dstStr);
printf("The string copied here is %s", dstStr);
return 0;
}
void copyFrom(char * str, char * mStr)
{
if(!mStr) {
mStr = (char *)malloc((strlen(str)) + 1);
if(mStr == NULL)
return;
}
while(*mStr++ = *str++) {
;
}
mStr[strlen(str)] = '\0';
}
Run Code Online (Sandbox Code Playgroud)
这不会复制字符串,但是如果使用数组而不是dstStr的char指针,那么一切正常.
你能告诉我这里有什么问题吗?
在malloc之后你需要返回mStr的值.现在,退出函数时,malloc的返回值和指向该字符串副本的指针将消失.它从malloc中泄漏了内存,因为它丢失了它的踪迹.
将您的功能更改为 char* copyFrom(const char * str)
然后从该函数返回mStr.然后你就可以写了dstStr = copyFrom(srcStr)
现在,POSIX C已经具备此功能.它被称为strdup.