TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Bo Simonsen
from: Jasen Betts
date: 2003-09-02 06:55:54
subject: Pointers

Hi Bo.

01-Sep-03 16:31:57, Bo Simonsen wrote to tom_torfs


 BS> Hello tom_torfs!

 BS> 01 Sep 03 07:00, Kurt Kuzba wrote to All:

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

 BS> Yes i know.

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

 BS> Can't i avoid to have a extra pointer?

you could replace sprintf with something that prints and then frees for you.

void print_n_free(char * s)
{
  if(s) {
    printf("%s",s):
    free(s);
    }
}

or you could change test to return a static.

char* test(){
  static char str[80];
  sprintf(str,"test");
  return str;
  }

theen you won't have to free it...

 -=> Bye <=-

---
* Origin: If at first you don't succeed, the hell with it. (3:640/1042)
SEEN-BY: 633/267 270
@PATH: 640/1042 531 954 774/605 123/500 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™.