The problem is that your blank
field provides space for one character, but you need up to 40 characters there. When using strcat
or strncat
, the destination buffer (which is the first argument to either function) must provide enough space for the concatenated string and a terminating \0
character.
What you want to do is something like
line = " ";
blank = malloc(MAX_LEN+1); /* 40 characters + terminating '\0' */
blank[0] = 0; /* Needed for strcat to work */
[...]
puts(strcat(strncat(blank, line, pos-1), aster));
Another note: Your use of line
and aster
leads to a memory leak. If you want to fill the memory allocated with malloc
with spaces, you should use memset
, if you want to assign a string literal, you should not use malloc
at all. What you actually do is overwriting the pointer returned by malloc
.