TIP: Click on subject to list as thread! ANSI
echo: os2prog
to: Joe Kelch
from: Dave Looney
date: 1995-04-14 07:21:00
subject: Borland Strings

[Joe Kelch writes concerning the use of gets() with an unallocated
char* pointer]

JK> I understand the problem now, but can't see how malloc() helps in
JK> this situation.  Until you gets() the string you don't know how  big
JK> it is, and until you malloc() you can't safely gets().

Joe, you have discovered an even greater weakness in your code.  The
use of gets() (and probably scanf()) is inherently unsafe since the
string you are reading might exceed the size of the allocated buffer. 
If you use malloc or declare the character array size in the variable
declaration, unlike the case in which the pointer has not be
initialized using malloc() and is probably pointing to an illegal
memory location, the OS may allow you to overwrite an allocated array
into program code, with disasterous results.  The gets() function has
been used to defeat system security on Unix systems by this method in
the past.

JK> Oh well, seems C requires you to waste space in some situations.  
 
Not at all. Use fgets() followed by sscanf() if needed to parse the
strings. To read a maximal length (up to memory or whatever) read the
string in chunks into a fixed buffer and use strdup() and strcat() to
append to a target buffer. OR, read the string a character at a time,
tallying the string length, then reset the stream and read into an
appropriate size buffer. For streams that can't be reset you could use
a temporary file.

It's more trouble than allocating a large buffer size, but even a
large buffer can be overwritten, and its much better to check size,
allocate memory as needed, freeing it when its no longer needed.  The
payoff is in programs that can handle unexpected data gracefully, and
are crash resistant and thrifty with memory.

Dave Looney [Team OS/2]

___
 X KWQ/2 1.2b X Windows is fne for Hih Sped Communicatns ...

--- Maximus/2 2.02
* Origin: OS/2 Connection {at} Mira Mesa, CA (1:202/354)
SEEN-BY: 105/42 620/243 711/401 409 410 413 430 807 808 809 934 955 712/407
SEEN-BY: 712/515 628 704 713/888 800/1 7877/2809
@PATH: 202/354 333 777 3615/50 396/1 270/101 105/103 42 712/515 711/808 809
@PATH: 711/934

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.