csp@gtenmc.UUCP (04/29/91)
> This proves without doubt 'Ignorance is NOT bliss'. followed by: > str[i] = malloc(strlen(gets(buff)+1)), The points you have raised are valid, but IMHO giving a routine which handles input with rigor, would even confuse the novice even further. But if you insist here is a routine which will handle the input will some rigor. Hope it satisfies your urge towards perfection. #include <stdio.h> #include <malloc.h> #define MEM_ERR 1 extern err_no; char *mygets(); char *mygets(l,t) unsigned l; char t; /* String terminator */ { char *ptr,c; c = getchar(); if (( int )c != -1 && c != t ) *( ptr = mygets( l + 1 , t )) = c; else { if (( ptr = malloc( l + 1 )) == ( char * ) NULL ) return( err_no = MEM_ERR , ( char * ) NULL ); *( ptr += l ) = 0; } return( ptr - 1 * ( l > 0 )); } C S Palkar
rearl@gnu.ai.mit.edu (Robert Earl) (04/30/91)
In article <1140@gtenmc.UUCP> csp@gtenmc.UUCP writes a very obfuscated
routine. It doesn't work-- at least my test program couldn't get it
to work; and there weren't any comments detailing its usage. It's in
serious need of useful comments and error-checking. It contains a bug
involving getchar(), which was discussed here[*] earlier.
Folks, getchar() returns an int: any valid char value, plus EOF (-1).
[*] Either here or some other newsgroup; at any rate, see K&R II
chapter 7.
--robert
--
rearl@gnu.ai.mit.edu
rearl@watnxt3.ucr.edu
john@newave.UUCP (John A. Weeks III) (05/01/91)
In article <1140@gtenmc.UUCP> csp@gtenmc.UUCP () writes: > > This proves without doubt 'Ignorance is NOT bliss'. > But if you insist here is a routine which will handle the input will > some rigor. Is it just me, living in a sheltered world, or is the following routine gross? + #include <stdio.h> + #include <malloc.h> + #define MEM_ERR 1 + extern err_no; + char *mygets(); + char *mygets(l,t) + unsigned l; + char t; /* String terminator */ + { + char *ptr,c; + c = getchar(); + if (( int )c != -1 && c != t ) + *( ptr = mygets( l + 1 , t )) = c; + else + { + if (( ptr = malloc( l + 1 )) == ( char * ) NULL ) + return( err_no = MEM_ERR , ( char * ) NULL ); + *( ptr += l ) = 0; + } + return( ptr - 1 * ( l > 0 )); + } You are using recursion to read a string character by character? What if you get a 1k string--have you ever worked on a machine/OS with limited stack space? And what is the (int) c != -1? I think you want EOF here. And the cast of c in this check, ever work with a machine with 8 bit characters, especially signed 8 bit chars? You could easily get symbols that map to integer -1 (like in DOS). I think you are trying to hit a two pound problem with a 5 pound hammer. No wonder we need risks and sparcs to do jobs that were once done on PDP's. -john- -- ============================================================================= John A. Weeks III (612) 942-6969 john@newave.mn.org NeWave Communications ...uunet!tcnet!wd0gol!newave!john