Nhu Thai Sanh Nguyen Nhu Thai Sanh Nguyen - 4 days ago 6
C Question

custom input function, weird '?' appended at the end of the string

I picked up programing not long ago. I'm trying to create a function to get a string from the user (for practice sake). my getString() function seems to do it jobs, but if the input string is too long (more than 17 characters to be specific), a weird "?" is added to my string. Don't know where did I messed up, I've been looking into it for quite sometimes, here's my code

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;
}


Test program:

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

Answer

The problem is this:

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

When the loop ends the value of n is already correct and where you should put the terminator. Incrementing it once more will put the terminator one step beyond the data you have read into the memory.

Comments