Added Andrew Bartlett's patch to use an allocated buffer for count_chars.