First of all, you have to allocate n + 1 chars for a string of length n, because of the trailing 0 meaning end of string.