Path: utzoo!utgpu!water!watmath!clyde!ima!think!barmar From: barmar@think.COM (Barry Margolin) Newsgroups: comp.lang.c Subject: Re: Quick C Strange Problems Message-ID: <17655@think.UUCP> Date: 8 Mar 88 17:05:32 GMT References: <12170@brl-adm.ARPA> Sender: usenet@think.UUCP Reply-To: barmar@fafnir.think.com.UUCP (Barry Margolin) Organization: Thinking Machines Corporation, Cambridge, MA Lines: 52 In article <12170@brl-adm.ARPA> Shekar_Narayanan.SV@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@think.com uunet!think!barmar