TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Bo Simonsen
from: Darin McBride
date: 2003-09-02 21:31:54
subject: Pointers

Hello Bo!

Replying to a message of Bo Simonsen to Darin McBride:

 BS> Hello Darin!

 BS> 01 Sep 03 14:01, you wrote to me:

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

 DM>> Yes.  But not in C.  Okay, that's not entirely true - you'd have to
 DM>> make significant changes, which are not always an option.  If you
 DM>> wrote both the caller and callee, then these changes are what I'd
 DM>> suggest anyway, even in C++.

 BS> Hmm.. I looks like it would be easier with the extra pointer.

Personal preference, I suppose.  However, the method I proposed below,
despite being "more difficult", is, I believe, usually the better
choice.

1.  It is fast.  With no malloc/free (slow, expensive function calls), it
performs as fast as the caller allows.  The only thing that would be faster
is if we didn't need to copy at all, e.g.: char const* test() { return
"test"; } .  There are some other speed-ups possible (e.g.,
caching the length of the string being copied so that the next time we're
called, we don't need to recalculate it), but overall it's very fast.

2.  It is complete safe.  Since we check the size of the incoming buffer,
we know we won't overwrite anything.

And, of course, it's a bit more than needed.

 KK>>>> #include 
 KK>>>> #include 

 DM>> char* test(char** buf, size_t buflen)

We don't need the extra * on buf throughout here.  So this would be char* buf ...

 KK>>>> {
 DM>>   /* char* tmp = (char*)malloc(80); */
 DM>>   /* if(tmp) sprintf(tmp, "test"); */

 DM>> char* source = "test";
 DM>> if (buflen > strlen(source))
 DM>>   sprintf(*buf, source);

And this would just be buf, not *buf...

 DM>>   /* return tmp; */
 DM>>   return *buf;

As would this ....

 KK>>>> }
 KK>>>> int main()
 KK>>>> {

 DM>> char buf[16];
 DM>> printf("%s\n", test(buf, sizeof(buf)));

 KK>>>>    fgets(buf, 16, stdin);
 KK>>>>    return 0;
 KK>>>> }

 DM>> No malloc/free's here.

 BS> No i see thank you :)

No problem.

Darin

---
* Origin: Tanktalus' Tower BBS (1:250/102)
SEEN-BY: 633/267 270
@PATH: 250/102 99 10/345 106/1 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™.