TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: All
from: Kurt Kuzba
date: 2003-09-01 07:00:58
subject: Pointers

From: kkuzba{at}centurytel.net
To: c_echo{at}yahoogroups.com

* Author: Bo Simonsen
BS>  I've a function here.
BS>  char * test()
BS>  {
BS>     char * tmp = NULL;
BS>     tmp = (char *) malloc(80);
BS>     sprintf(tmp, "test");
BS>     return tmp;
BS>  }
BS>  int main()
BS>  {
BS>     printf("%s", test());
BS>  }
BS>  How do i free the memory i allocated for tmp?

    You have to have the pointer, of course!  To avoid accidentally
 attempts to free a null pointer on failure of the malloc(), you
 might wish to test the value of the pointer before calling free()
 or using the pointer to accept data intended for later use.
 Writing to a null pointer on an unprotected OS, such as DOS, is a
 very quick method for arriving at unexpected catastrophic failure.
 (I included fgets() lest the window shut too quick to be seen.)

#include 
#include 
char* test()
{
   char* tmp = (char*)malloc(80);
   if(tmp) sprintf(tmp, "test");
   return tmp;
}
int main()
{
   char* cTmp, buf[16];
   printf("%s", cTmp = test());
   if(cTmp) free(cTmp);
   fgets(buf, 16, stdin);
   return 0;
}

>  kkuzba{at}centurytel.net   http://home.centurytel.net/kkuzba
>  'My very bones are chilled,' said Gimli, flapping his arms and
>  stamping his feet. Day had come at last.

--- SoupGate-Win32 v1.05
* Origin: kkuzba{at}centurytel.net (2:292/516.666)
SEEN-BY: 633/267 270
@PATH: 292/516 854 140/1 106/2000 633/267

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™.