[prev] [index] [next]

Exercise: Buggy Function

Explain what is wrong with this function:

// returns a string of 'x' characters
// e.g. xs(5) -> "xxxxx", xs(0) = ""
char *xs(int n) {
	int i;
	char buffer[100];
	// truncate if try to add too many 'x's
	if (n > 100) {
		n = 100;
	} else if (n < 0) {
		n = 0;
	}
	for (i = 0; i < n; i++) {
		buffer[i] = 'x';
	}
	buffer[i] = '\0';   // terminate string
	return buffer;
}

How could we fix the problem?