Code:
str = (char*)malloc(sizeof(char)*(digits + 1));
str[digits + 1] = '\0';
Say that there is a 4 digit number. Malloc(5) would be correct, because you need 5 positions: four for the digits and 1 for the terminating zero.
If we think about the result we want, then we might come up with this.
Code:
position: 0 1 2 3 4
string: { '1', '2', '3', '4', '\0' }
But you used digits + 1 instead which puts the '\0' in postion 5, the wrong place for positive numbers.
When the number is negative, the result should be this.
Code:
position: 0 1 2 3 4 5
string: { '-', '1', '2', '3', '4', '\0' }
So that is why it is appearing correct for negative numbers.