J
Jeff
Hello everybody,
I was doing one of the exercises in the K&R book, and I got something
really strange. Here's the source code:
/*
* Exercise 2-2 from the K&R book, page 42
*/
#include <stdio.h>
enum loop_control { EXIT, CONTINUE };
int getline (char s[], int lim)
{
short int loop = CONTINUE;
unsigned int i = 0;
int c;
while (loop) {
c = getchar();
if (i == (lim - 2))
loop = EXIT;
else if (c == EOF)
loop = EXIT;
else if (c == '\n')
loop = EXIT;
else
s[i++] = c;
}
if (c == '\n')
s[i++] = c;
s = '\0';
return (i);
}
The strange thing is that lim doesn't seem to control anything at all.
I compiled it using GCC under cygwin on a windows 98 system (I added a
simple main() function that gets a line using getline() and then
prints it).
The strange thing is that even when I put a very small value for lim,
say 10, I can still get very big strings into it without it crashing.
Here's an example output:
$ gcc -o ex exercise2-2.c
$ ./ex
123333333333333333
1233333333333333
fdkjghfgsfgkjsdf
fdkjghfgfgkjsdf
(^C)
$
Any feedback will be appreciated!
Cheers!
- Joseph
I was doing one of the exercises in the K&R book, and I got something
really strange. Here's the source code:
/*
* Exercise 2-2 from the K&R book, page 42
*/
#include <stdio.h>
enum loop_control { EXIT, CONTINUE };
int getline (char s[], int lim)
{
short int loop = CONTINUE;
unsigned int i = 0;
int c;
while (loop) {
c = getchar();
if (i == (lim - 2))
loop = EXIT;
else if (c == EOF)
loop = EXIT;
else if (c == '\n')
loop = EXIT;
else
s[i++] = c;
}
if (c == '\n')
s[i++] = c;
s = '\0';
return (i);
}
The strange thing is that lim doesn't seem to control anything at all.
I compiled it using GCC under cygwin on a windows 98 system (I added a
simple main() function that gets a line using getline() and then
prints it).
The strange thing is that even when I put a very small value for lim,
say 10, I can still get very big strings into it without it crashing.
Here's an example output:
$ gcc -o ex exercise2-2.c
$ ./ex
123333333333333333
1233333333333333
fdkjghfgsfgkjsdf
fdkjghfgfgkjsdf
(^C)
$
Any feedback will be appreciated!
Cheers!
- Joseph