自定义输入功能,怪异的'?'附加在字符串的末尾

时间:2016-11-29 15:25:40

标签: c input

我不久前接受了编程。我试图创建一个函数来从用户那里获取一个字符串(为了实践起见)。我的getString()函数似乎做了它的工作,但如果输入字符串太长(超过17个字符是特定的),一个奇怪的"?"被添加到我的字符串中。不知道我搞砸了哪里,我有时候一直在调查它,这里是我的代码

char* getString(void)
{
    /* how large is the buffer */
    unsigned int capacity = 32;
    /* growable buffer to store string */
    char* buffer = malloc(capacity * sizeof(char));
    if (buffer == NULL)
    {
        return NULL;
    }
    /* how many characters are actually there in the buffer */
    unsigned int n = 0;
    int c; // character read or EOF

    while((c = fgetc(stdin)) != '\n' && c != EOF)
    {
        // if there's enough space in buffer -> store c into buffer, continue to next loop
        if (n + 1 >= capacity)
        {
            capacity *= 2;
            char* temp = realloc(buffer, capacity * sizeof(char));
            if(temp == NULL)
            {
                free(buffer);
                return NULL;
            }
            buffer = temp;
        }
        // store c to reallocated buffer
        buffer[n++] = c;
    }

    if (n == 0 && (c == EOF))
    {
        return NULL;
    }

    // terminate string with '\0'
    buffer[++n] = '\0';
    puts(buffer);
    // remove blank space after '\0'
    buffer = realloc(buffer, (n+1) * sizeof(char));

    // return buffer
    return buffer;
}

测试程序:

Pls gimme a string
12345678901234567890
You gave me this string: "12345678901234567890?", which is 21 chars long

1 个答案:

答案 0 :(得分:2)

问题在于:

buffer[++n] = '\0';

当循环结束时,n的值已经正确,并且您应该放置终止符。再次递增它会使终结器超出您读入内存的数据。