在下面是一个小测试,我在使用C编程时混淆了.
int main()
{
char buff[100] = {};
char* pStr = NULL;
printf("Input the string\n");
if (!fgets(buff, sizeof(buff), stdin))
{
printf("ERROR INPUT\n");
return 1;
}
printf("%zd\n", strlen(buff));
pStr = (char*)malloc(strlen(buff)+1);
strcpy_s(pStr, sizeof(buff), buff);
printf("%s\n", strlen(pStr));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我试图用来fgets捕获输入字符串并将其存储在指定的内存中malloc.但是,当我尝试使用时malloc(strlen(char*)+1),程序编译时没有错误但运行失败.一旦我切换到malloc(sizeof(buff)),它工作正常.我很困惑.从而寻求你的帮助.
strcpy_s(pStr, sizeof(buff), buff); 如果不正确,您应该使用新目标缓冲区的大小,而不是源缓冲区的大小
只需用整个东西替换即可
size_t size = strlen(buff)+1;
pStr = malloc(size);
memcpy(pStr, buff, size);
Run Code Online (Sandbox Code Playgroud)
作为一点奖励,这段代码也更快.