Malloc(Strlen(char*) 1)遇到的问题



在下面是我在与c。

int main()
{
    char buff[100] = {};
    char* pStr = NULL;
    printf("Input the stringn");
    if (!fgets(buff, sizeof(buff), stdin))
    {
        printf("ERROR INPUTn");
        return 1;
    }
    printf("%zdn", strlen(buff));
    pStr = (char*)malloc(strlen(buff)+1);
    strcpy_s(pStr, sizeof(buff), buff);
    printf("%sn", strlen(pStr));
    return 0;
}

我尝试使用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);

作为一点奖励,此代码也更快。

最新更新