summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSadeep Madurange <smadurange@users.noreply.github.com>2021-12-04 08:46:22 +0800
committerSadeep Madurange <smadurange@users.noreply.github.com>2021-12-04 08:46:22 +0800
commit1d958679201f143ecf1c5527bd462e29b87427de (patch)
tree08781740462e1d183f48d63ed8cc6ae1800a6853
parent8e6cbc215e31bfd016a392d992e2b9a74da20580 (diff)
downloadk&r-exercises-1d958679201f143ecf1c5527bd462e29b87427de.tar.gz
3.4
-rw-r--r--3/4.c10
1 files changed, 4 insertions, 6 deletions
diff --git a/3/4.c b/3/4.c
index 5ddf2ef..91c3953 100644
--- a/3/4.c
+++ b/3/4.c
@@ -4,14 +4,10 @@
#define MAXLEN 50
-// xplanation of the error:
-// In itoa, for largest negative number, n = -n overflows
-// resulting in n = INT_MIN (wraps around) causing a god awful mess.
-
void itoa(int n, char s[]);
void reverse(char s[]);
-/* Fixes itoa function to handle the largest negative number */
+/* fixes itoa function to handle the largest negative number */
int main(int argc, char *argv[]) {
char s[MAXLEN];
@@ -27,12 +23,14 @@ void itoa(int n, char s[]) {
i = 0;
- if (n != INT_MIN) {
+ if (n >= 0) {
do {
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
}
else {
+ // avoid integer overflow of n = -n of min n in original impl
+ // by handling negtive values separately.
do {
s[i++] = -(n % 10) + '0';
} while ((n /= 10) <= -1);