I am following K&R second edition examples to learn C and coding as I think this is correct way of doing things. Anyhow when I run this program post compilation the program get stuck. I used valgrind for execution of compiled script.
#include <ctype.h>
int atoi(char s[])
{
int i, n, sign;
for(i = 0; isspace(s[i]); i++)
;
sign = (s[i] == '-')? -1 : 1;
if (s[i] == '+'|| s[i] == '-')
i++;
for (int n = 0; isdigit(s[i]); n++)
n = 10 * n + (s[i]-'0');
return sign * n;
}
int main()
{
char input[] = " -12345";
atoi(input);
}
# vaibhavchauhan at startup001 in ~/Documents/Projects/K-R on git:master x [0:43:36]
$ valgrind ./atoi-general
==8075== Memcheck, a memory error detector
==8075== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==8075== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==8075== Command: ./atoi-general
==8075==
^C==8075==
As noticed, the index in your second loop is incorrect.
This should be - notice that you should NOT reinitialize the index
i
in the second loop as it should be the left over value from the first loop (as you already skipped the white spaces and the sign).The K&R example could be improved for readability and performance. The following issues exist:
atoi
exists in stdlib.h.size_t
should be used for the iterators, notint
.n
is a very bad name for an iterator! In C programming,n
has a special meaning and that is to describe the number of items in a container.-
twice.In your second loop, you are iterating
n
but you usei
for your computations and computations. This leads to the infinite loop you observe. To fix this, use eitheri
as an index consistently:Note that indices should have type
size_t
, notint
as the latter might be not large enough to index every array. For this purpose, an index of typeint
is fine though.