Quick C Strange Problems

Barry Margolin barmar at think.COM
Wed Mar 9 03:05:32 AEST 1988


In article <12170 at brl-adm.ARPA> Shekar_Narayanan.SV at Xerox.COM writes:
>1) With character pointers. The code reads like this.
>
>char *getstring(col, row, len)
>int col, row, len;
>{
>	char *temp, *s;
>	char ch;
>	int count;
>
>	temp = s;
>	count = 0;
>	for (;;)
>	{
>		if (count > len) return temp;
>		ch = getkey(); /* get a key from user */
>		if (ch == ESC) return NULL;
>		switch (ch)
>		{
>			case CR:
>				*s = ch;
>				return temp;
>				break;
[rest of program edited out.]

The problem is that you never allocated any storage for your return
string.  Since you never initialized it, s is pointing to an
effectively random part of memory when this function is entered.  When
you then store through it you could be overwriting anything, which
would explain why your program freezes.

The first fix is to allocate the storage you need, with

	s = malloc (len+1); /* Leave room for the trailing '\0' */

Another problem with your program is that you don't put a trailing
'\0' at the end of the string you return.  In the CR case, before the
"return" statement you should do

	*(s+1) = '\0';

Finally, in the case of ESC, you should free the string before
returning NULL.

Minor point: why do you check for ESC in the "if" statement, rather
than making it one of the switch cases?

Barry Margolin
Thinking Machines Corp.

barmar at think.com
uunet!think!barmar



More information about the Comp.lang.c mailing list