在 C 中创建获取字符串函数时遇到问题

Troubles creating a get string function in C

我正在尝试制作一个简单的函数,以安全的方式 returns 一个字符串,我想知道这段代码有什么问题。
我决定使用 read 因为 scanf 和 fgets 都给 e 带来了麻烦, 具体来说,如果我明显溢出缓冲区,即使进行了长度检查,scanf 也会给我中止陷阱 6,
当 fgets 接受输入时,如果我插入的字符串太长,returns 会显示错误消息,但无论如何都会预转换字符串,不允许我重新输入另一个字符串。
这是代码:

string get_string(const string prompt)
{
    char temp[30];
    int size,count;
    printf("%s",prompt);
    do
    {
        count=read(0,temp,29);
        temp[count]='[=10=]';
        size=strlen(temp);
        if(size>24)
        {
            printf("\x1B[31mError\x1B[0m: too long.\n%s",prompt);
        }
        printf("size :%i\n",size);
    }
    while(size>24);
    stripc(temp,'\n'); //removes new line
    string word=malloc((size)*sizeof(char));
    strcpy(word,temp);
    return word;
}

现在读取它给了我同样的错误,我从 stdin 读取了总共 30 个字节,
然后我在计数器的末尾添加空字符,但如果长度超过这是输出:

ppppppppppppppppppppppppppppp
Error: too long.
size :30
size :2
p

知道问题出在哪里吗?
还有其他方法可以实现我的需求吗?

编辑:问题不是超出范围,
奇怪的是,一旦我写了超过 24 个字符,
应该读取输入的函数(read、scanf、fgets 或其他),
不再激活,这就是 size: 连续出现两次的原因,
由于某种原因跳过了输入插入,我想了解原因。
我纠正了一些错误。

如果在第一个输入中没有找到换行符,则调用 fgets 直到找到换行符以清理输入流,然后继续外部 while 循环。

string get_string(const string prompt)
{
    char temp[26] = "";//24 + newline + '[=10=]'
    int size,count;
    while ( 1)
    {
        printf ( "%s",prompt);
        if ( fgets ( temp, sizeof temp, stdin)) {
            if ( !strchr ( temp, '\n')) {//no newline
                printf("\x1B[31mError\x1B[0m: too long.\n%s",prompt);
                size = strlen ( temp);
                do {
                    fgets ( temp, sizeof temp, stdin);//read more and discard
                    size += strlen ( temp);
                } while (!strchr ( temp, '\n'));//loop until newline found
                printf("size :%i\n",size);
                continue;//re prompt
            }
            break;
        }
        else {
            fprintf ( stderr, "fgets problem\n");
            return NULL;
        }
    }

    temp[strcspn ( temp,"\n")] = '[=10=]';//remove newline
    string word = malloc(strlen ( temp) + 1);
    strcpy ( word, temp);
    return word;
}

同样的错误一遍又一遍...

C 中的字符串是null terminated. 这意味着容纳字符串的内存必须比字符串的长度大一.

您检查读取的字符串不超过 24 个字符,但是在您的 malloc 中您没有为空字符添加空间。因此,strcpy 将空字符 放在分配的内存之外