“Heap corruption” usually means that you wrote to unallocated memory, damaging the data structures used to operate the memory allocator.
There may be more problems, but the first of them I see in this line:
strcpy(buffer, n);
This will write strlen(n) + 1 bytes to buffer , but buffer is only strlen(n) bytes (the extra byte is the final \0 ) Writing this extra byte leads to undefined behavior and can damage the heap.
Ernest friedman-hill
source share