TIP: Click on subject to list as thread! ANSI
echo: rberrypi
to: R.WIESER
from: PASCAL J. BOURGUIGNON
date: 2019-02-25 09:40:00
subject: Re: C is not a low level

"R.Wieser"  writes:

> TNP,
>
>> Assuming you bzeroed the target block before copying first. strncpy does
>> not zero terminate te target block
>
> You want to be pedantic and point out the obvious ?   No, you do not need to
> do that.  Just making sure that the /last/ character is zero will do fine.

How do you make sure that the last character is zero?
Do you prove it mathematically? Have you tested it too?
Do you ensure it manually? Are you use you didn't miss one or made a
mistake?

Using strn with strlen is dumb.

The only way to make sure that the last character is zero is to keep the
buffer size and the string length along with the string:

typedef {
   size_t allocated;
   size_t length;
   char*  characters;
} string;

and to let the code perform the check itself!

void string_validate(string* string){
   if(string==NULL){error("null string");}
   if(string->characters==NULL){error("invalid string");
   if(string->allocatedlength){error("string length too big for
allocated size");}
   if(string->characters[string->length]){error("string internal representation
is not null-terminated!");}
}

> But tell me, how does that counter my suggestion to tell "strncpy" that the
> buffer is one char smaller than it actually is ?

You didn't ensure it by code.

--
__Pascal J. Bourguignon__
http://www.informatimago.com

--- SoupGate-Win32 v1.05
* Origin: Agency HUB, Dunedin - New Zealand | FidoUsenet Gateway (3:770/3)

SOURCE: echomail via QWK@docsplace.org

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