Rocksolid Light

Welcome to novaBBS (click a section below)

mail  files  register  newsreader  groups  login

Message-ID:  

Real Users are afraid they'll break the machine -- but they're never afraid to break your face.


devel / comp.lang.c / Automatic strings without malloc

SubjectAuthor
* Automatic strings without mallocpozz
+- Re: Automatic strings without mallocpozz
+- Re: Automatic strings without mallocMalcolm McLean
+* Re: Automatic strings without mallocDavid Brown
|+* Re: Automatic strings without mallocManfred
||`- Re: Automatic strings without mallocDavid Brown
|`- Re: Automatic strings without mallocpozz
+* Re: Automatic strings without mallocThiago Adams
|`- Re: Automatic strings without mallocPhilipp Klaus Krause
+- Re: Automatic strings without mallocBart
+* Re: Automatic strings without mallocScott Lurndal
|`* Re: Automatic strings without mallocMalcolm McLean
| `* Re: Automatic strings without mallocDavid Brown
|  +* Re: Automatic strings without mallocScott Lurndal
|  |`* Re: Automatic strings without mallocDavid Brown
|  | +* Re: Automatic strings without mallocScott Lurndal
|  | |`* Re: Automatic strings without mallocThiago Adams
|  | | `- Re: Automatic strings without mallocMalcolm McLean
|  | `* Re: Automatic strings without mallocWilliam Ahern
|  |  `* Re: Automatic strings without mallocDavid Brown
|  |   `* Re: Automatic strings without mallocMalcolm McLean
|  |    +* Re: Automatic strings without mallocThiago Adams
|  |    |`* Re: Automatic strings without mallocBen Bacarisse
|  |    | `* Re: Automatic strings without mallocThiago Adams
|  |    |  +- Re: Automatic strings without mallocKeith Thompson
|  |    |  `- Re: Automatic strings without mallocBen Bacarisse
|  |    `- Re: Automatic strings without mallocDavid Brown
|  `* Re: Automatic strings without mallocKeith Thompson
|   `* Re: Automatic strings without mallocDavid Brown
|    `* Re: Automatic strings without mallocKeith Thompson
|     `* [OT] Generally... [Was: Automatic strings without malloc]Jeremy Brubaker
|      `- Re: [OT] Generally... [Was: Automatic strings without malloc]Keith Thompson
+* Re: Automatic strings without mallocKeith Thompson
|`- Re: Automatic strings without mallocpozz
`* Re: Automatic strings without mallocSiri Cruise
 `* Re: Automatic strings without mallocDavid Brown
  `* Re: Automatic strings without mallocSiri Cruise
   +* Re: Automatic strings without mallocMalcolm McLean
   |`- Re: Automatic strings without mallocDavid Brown
   `* Re: Automatic strings without mallocDavid Brown
    +* Re: Automatic strings without mallocSiri Cruise
    |+* Re: Automatic strings without mallocDavid Brown
    ||`- Re: Automatic strings without mallocChris M. Thomasson
    |`- Re: Automatic strings without mallocGuillaume
    `* Re: Automatic strings without mallocChris M. Thomasson
     `* Re: Automatic strings without mallocMalcolm McLean
      `* Re: Automatic strings without mallocDavid Brown
       `- Re: Automatic strings without mallocluser droog

Pages:12
Automatic strings without malloc

<sn2lvp$sl7$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19005&group=comp.lang.c#19005

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!aioe.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: pozzu...@gmail.com (pozz)
Newsgroups: comp.lang.c
Subject: Automatic strings without malloc
Date: Wed, 17 Nov 2021 11:36:41 +0100
Organization: A noiseless patient Spider
Lines: 29
Message-ID: <sn2lvp$sl7$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Wed, 17 Nov 2021 10:36:41 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="78d595778016f4ecdb8161a6b0f34334";
logging-data="29351"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+MEoWvGfZGJ+9tMyUVaaDz7CF0cwh0lzA="
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.3.1
Cancel-Lock: sha1:UJbFTdktByKJvgGn13YxhSM2Mbg=
 by: pozz - Wed, 17 Nov 2021 10:36 UTC

Many times I need to construct a string through a call to sprintf and
pass it to an external function.

char s[32];
sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
lcd_write(s);

The size of s is fixed and calculated for the maximum length of
yourname, that is 9.

Later in time, I need to change the message into:

sprintf(s, "Hello %s, today is %d/%d/%d", yourname, day, month, year);

Of course, I need to re-calculate the worst-case length, that should be
now 35. However this is error-prone and I could forget to change the
size of array.

Is there a better way to manage this situation? I can't use malloc()
because I'm on an embedded system where I can't use heap.

I'm thinking to use sprintf(NULL, ...), such as:

const char fmt[] = "Hi %s, today is %d/%d/%d";
size_t n = sprintf(NULL, fmt, yourname, day, month, year);
char s[n + 1];
sprintf(s, fmt, yourname, day, month, year);
lcd_write(s);

Re: Automatic strings without malloc

<sn2m28$sl7$2@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19006&group=comp.lang.c#19006

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: pozzu...@gmail.com (pozz)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Wed, 17 Nov 2021 11:38:00 +0100
Organization: A noiseless patient Spider
Lines: 28
Message-ID: <sn2m28$sl7$2@dont-email.me>
References: <sn2lvp$sl7$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Date: Wed, 17 Nov 2021 10:38:00 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="78d595778016f4ecdb8161a6b0f34334";
logging-data="29351"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/KbLRgPAb6mt7A9Tk5uoin+FWh+0P6UVQ="
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.3.1
Cancel-Lock: sha1:cclKJ5UJFgFDBFjzdTQc9sMxCgY=
In-Reply-To: <sn2lvp$sl7$1@dont-email.me>
 by: pozz - Wed, 17 Nov 2021 10:38 UTC

Il 17/11/2021 11:36, pozz ha scritto:
> Many times I need to construct a string through a call to sprintf and
> pass it to an external function.
>
>   char s[32];
>   sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>   lcd_write(s);
>
> The size of s is fixed and calculated for the maximum length of
> yourname, that is 9.
>
> Later in time, I need to change the message into:
>
>   sprintf(s, "Hello %s, today is %d/%d/%d", yourname, day, month, year);
>
> Of course, I need to re-calculate the worst-case length, that should be
> now 35. However this is error-prone and I could forget to change the
> size of array.
>
> Is there a better way to manage this situation? I can't use malloc()
> because I'm on an embedded system where I can't use heap.
>
> I'm thinking to use sprintf(NULL, ...), such as:

I'm sorry, I mean:

snprintf(NULL, 0, ...)

Re: Automatic strings without malloc

<e44ba99b-496e-4b83-bc81-1e16b18639d1n@googlegroups.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19007&group=comp.lang.c#19007

  copy link   Newsgroups: comp.lang.c
X-Received: by 2002:a05:622a:388:: with SMTP id j8mr15726785qtx.131.1637146815531;
Wed, 17 Nov 2021 03:00:15 -0800 (PST)
X-Received: by 2002:a05:6214:f61:: with SMTP id iy1mr53992308qvb.0.1637146815343;
Wed, 17 Nov 2021 03:00:15 -0800 (PST)
Path: i2pn2.org!i2pn.org!weretis.net!feeder8.news.weretis.net!proxad.net!feeder1-2.proxad.net!209.85.160.216.MISMATCH!news-out.google.com!nntp.google.com!postnews.google.com!google-groups.googlegroups.com!not-for-mail
Newsgroups: comp.lang.c
Date: Wed, 17 Nov 2021 03:00:15 -0800 (PST)
In-Reply-To: <sn2lvp$sl7$1@dont-email.me>
Injection-Info: google-groups.googlegroups.com; posting-host=2a00:23a8:400a:5601:dca9:9ec4:3f03:c2dd;
posting-account=Dz2zqgkAAADlK5MFu78bw3ab-BRFV4Qn
NNTP-Posting-Host: 2a00:23a8:400a:5601:dca9:9ec4:3f03:c2dd
References: <sn2lvp$sl7$1@dont-email.me>
User-Agent: G2/1.0
MIME-Version: 1.0
Message-ID: <e44ba99b-496e-4b83-bc81-1e16b18639d1n@googlegroups.com>
Subject: Re: Automatic strings without malloc
From: malcolm....@gmail.com (Malcolm McLean)
Injection-Date: Wed, 17 Nov 2021 11:00:15 +0000
Content-Type: text/plain; charset="UTF-8"
 by: Malcolm McLean - Wed, 17 Nov 2021 11:00 UTC

On Wednesday, 17 November 2021 at 10:36:53 UTC, pozz wrote:
> Many times I need to construct a string through a call to sprintf and
> pass it to an external function.
>
> char s[32];
> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
> lcd_write(s);
>
> The size of s is fixed and calculated for the maximum length of
> yourname, that is 9.
>
> Later in time, I need to change the message into:
>
> sprintf(s, "Hello %s, today is %d/%d/%d", yourname, day, month, year);
>
> Of course, I need to re-calculate the worst-case length, that should be
> now 35. However this is error-prone and I could forget to change the
> size of array.
>
> Is there a better way to manage this situation? I can't use malloc()
> because I'm on an embedded system where I can't use heap.
>
> I'm thinking to use sprintf(NULL, ...), such as:
>
> const char fmt[] = "Hi %s, today is %d/%d/%d";
> size_t n = sprintf(NULL, fmt, yourname, day, month, year);
> char s[n + 1];
> sprintf(s, fmt, yourname, day, month, year);
> lcd_write(s);
>
That's a reasonable solution, as long as you know you have enough stack
(and a C99 compiler).
You've got to ask how likely it is that a bug whereby you overrun the buffer
will persist. If a bug will be caught in the first informal test, then it's not
dangerous. If it could slip through until a late stage, it's more worrying.
Since a buffer overrun will corrupt the variable immediately after the
buffer in memory, this might be detected immediately, or it might not be detected
for some time, depending on what that variable is used for. So a dangerous
bug, unless you've got some memory-checking software that can detect
such situations.
That's your best answer, however the software might be very expensive, or
might not be available at all.

Re: Automatic strings without malloc

<sn2nk2$7mp$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19008&group=comp.lang.c#19008

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: david.br...@hesbynett.no (David Brown)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Wed, 17 Nov 2021 12:04:33 +0100
Organization: A noiseless patient Spider
Lines: 53
Message-ID: <sn2nk2$7mp$1@dont-email.me>
References: <sn2lvp$sl7$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Injection-Date: Wed, 17 Nov 2021 11:04:34 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="476d31386fcaa27dba3f738faf4e6e3a";
logging-data="7897"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18EsZkjwHkQb30jVa+p16aErCIoLbtmu04="
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101
Thunderbird/78.11.0
Cancel-Lock: sha1:8gHlyl8YaILTPhpAl2bvfS4RHt4=
In-Reply-To: <sn2lvp$sl7$1@dont-email.me>
Content-Language: en-GB
 by: David Brown - Wed, 17 Nov 2021 11:04 UTC

On 17/11/2021 11:36, pozz wrote:
> Many times I need to construct a string through a call to sprintf and
> pass it to an external function.
>
>   char s[32];
>   sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>   lcd_write(s);
>
> The size of s is fixed and calculated for the maximum length of
> yourname, that is 9.
>
> Later in time, I need to change the message into:
>
>   sprintf(s, "Hello %s, today is %d/%d/%d", yourname, day, month, year);
>
> Of course, I need to re-calculate the worst-case length, that should be
> now 35. However this is error-prone and I could forget to change the
> size of array.
>
> Is there a better way to manage this situation? I can't use malloc()
> because I'm on an embedded system where I can't use heap.
>
> I'm thinking to use sprintf(NULL, ...), such as:
>
>   const char fmt[] = "Hi %s, today is %d/%d/%d";
>   size_t n = sprintf(NULL, fmt, yourname, day, month, year);
>   char s[n + 1];
>   sprintf(s, fmt, yourname, day, month, year);
>   lcd_write(s);
>

That would work (with your follow-up correction). You might want to put
a limit on "n" to avoid accidental stack overflow. This arrangement
does mean that you are doing the printf part twice.

Very often in small systems you know there is a maximum size - if your
screen is 40 characters wide, then 40 characters is enough in your
array. And if you might need up to 40 characters then you might as well
use all of the 40 chars, even though your string might be shorter - you
really don't want to test your code for the name "Al" on date 1/2/2021
and then find you have a stack overflow on 10/10/2021 with the name
"Rhoshandiatellyneshiaunneveshenk". (Apparently that's a real name -
according to google!)

It is also worth noting that only one task should be calling lcd_write
at a time - otherwise your display will be messed up. You can extend
that and say that only one task will be using the format buffer at a
time, and then it can be a statically array that is shared by all client
code.

Re: Automatic strings without malloc

<8ae929dc-6b89-4a30-bbb0-16ceaeb94c63n@googlegroups.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19010&group=comp.lang.c#19010

  copy link   Newsgroups: comp.lang.c
X-Received: by 2002:a05:620a:2407:: with SMTP id d7mr13349455qkn.114.1637154677027;
Wed, 17 Nov 2021 05:11:17 -0800 (PST)
X-Received: by 2002:a05:622a:3d3:: with SMTP id k19mr16806618qtx.334.1637154676811;
Wed, 17 Nov 2021 05:11:16 -0800 (PST)
Path: i2pn2.org!i2pn.org!weretis.net!feeder8.news.weretis.net!proxad.net!feeder1-2.proxad.net!209.85.160.216.MISMATCH!news-out.google.com!nntp.google.com!postnews.google.com!google-groups.googlegroups.com!not-for-mail
Newsgroups: comp.lang.c
Date: Wed, 17 Nov 2021 05:11:16 -0800 (PST)
In-Reply-To: <sn2lvp$sl7$1@dont-email.me>
Injection-Info: google-groups.googlegroups.com; posting-host=189.6.249.78; posting-account=xFcAQAoAAAAoWlfpQ6Hz2n-MU9fthxbY
NNTP-Posting-Host: 189.6.249.78
References: <sn2lvp$sl7$1@dont-email.me>
User-Agent: G2/1.0
MIME-Version: 1.0
Message-ID: <8ae929dc-6b89-4a30-bbb0-16ceaeb94c63n@googlegroups.com>
Subject: Re: Automatic strings without malloc
From: thiago.a...@gmail.com (Thiago Adams)
Injection-Date: Wed, 17 Nov 2021 13:11:17 +0000
Content-Type: text/plain; charset="UTF-8"
 by: Thiago Adams - Wed, 17 Nov 2021 13:11 UTC

On Wednesday, November 17, 2021 at 7:36:53 AM UTC-3, pozz wrote:
> Many times I need to construct a string through a call to sprintf and
> pass it to an external function.
>
> char s[32];
> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
> lcd_write(s);
>
> The size of s is fixed and calculated for the maximum length of
> yourname, that is 9.
>
> Later in time, I need to change the message into:
>
> sprintf(s, "Hello %s, today is %d/%d/%d", yourname, day, month, year);
>
> Of course, I need to re-calculate the worst-case length, that should be
> now 35. However this is error-prone and I could forget to change the
> size of array.
>
> Is there a better way to manage this situation? I can't use malloc()
> because I'm on an embedded system where I can't use heap.
>
> I'm thinking to use sprintf(NULL, ...), such as:
>
> const char fmt[] = "Hi %s, today is %d/%d/%d";
> size_t n = sprintf(NULL, fmt, yourname, day, month, year);
> char s[n + 1];
> sprintf(s, fmt, yourname, day, month, year);
> lcd_write(s);

See : asprintf
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1248.pdf

This function is not implemented in some systems but it can be
built with other printf functions.

There is also open_memstream that I wish were part of C standard
because It cannot be implemented on windows without access to FILE internals.
https://linux.die.net/man/3/open_memstream

I create my own memory stream to be possible to use on windows and linux.

Re: Automatic strings without malloc

<sn315u$qj7$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19011&group=comp.lang.c#19011

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: bc...@freeuk.com (Bart)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Wed, 17 Nov 2021 13:47:44 +0000
Organization: A noiseless patient Spider
Lines: 40
Message-ID: <sn315u$qj7$1@dont-email.me>
References: <sn2lvp$sl7$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Date: Wed, 17 Nov 2021 13:47:42 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="96afae145f24b18c8cc9282604dfa31e";
logging-data="27239"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/J7i5rrBM2cc46Sna66dpzyTWheLz5e9E="
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.3.0
Cancel-Lock: sha1:cqzuWAWcxcuVFPJn7/ibG137DXI=
In-Reply-To: <sn2lvp$sl7$1@dont-email.me>
 by: Bart - Wed, 17 Nov 2021 13:47 UTC

On 17/11/2021 10:36, pozz wrote:
> Many times I need to construct a string through a call to sprintf and
> pass it to an external function.
>
>   char s[32];
>   sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>   lcd_write(s);
>
> The size of s is fixed and calculated for the maximum length of
> yourname, that is 9.
>
> Later in time, I need to change the message into:
>
>   sprintf(s, "Hello %s, today is %d/%d/%d", yourname, day, month, year);
>
> Of course, I need to re-calculate the worst-case length, that should be
> now 35. However this is error-prone and I could forget to change the
> size of array.
>
> Is there a better way to manage this situation? I can't use malloc()
> because I'm on an embedded system where I can't use heap.
>
> I'm thinking to use sprintf(NULL, ...), such as:
>
>   const char fmt[] = "Hi %s, today is %d/%d/%d";
>   size_t n = sprintf(NULL, fmt, yourname, day, month, year);
>   char s[n + 1];
>   sprintf(s, fmt, yourname, day, month, year);
>   lcd_write(s);
>

Does lcd_write() remember where it was up to? If so you can break it up:

lcd_write("Hi ");
lcd_write(yourname);
lcd_write(", today is ");

This then only leaves the date, which has a maximum width, eg,
"dd/mm/yyyy". You could also then use a common routine for turning a
date into a string, if it's needed in a few places.

Re: Automatic strings without malloc

<ei9lJ.146291$I%1.54591@fx36.iad>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19014&group=comp.lang.c#19014

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!weretis.net!feeder8.news.weretis.net!ecngs!feeder2.ecngs.de!178.20.174.213.MISMATCH!feeder1.feed.usenet.farm!feed.usenet.farm!peer03.ams4!peer.am4.highwinds-media.com!peer03.iad!feed-me.highwinds-media.com!news.highwinds-media.com!fx36.iad.POSTED!not-for-mail
X-newsreader: xrn 9.03-beta-14-64bit
Sender: scott@dragon.sl.home (Scott Lurndal)
From: sco...@slp53.sl.home (Scott Lurndal)
Reply-To: slp53@pacbell.net
Subject: Re: Automatic strings without malloc
Newsgroups: comp.lang.c
References: <sn2lvp$sl7$1@dont-email.me>
Lines: 13
Message-ID: <ei9lJ.146291$I%1.54591@fx36.iad>
X-Complaints-To: abuse@usenetserver.com
NNTP-Posting-Date: Wed, 17 Nov 2021 15:34:34 UTC
Organization: UsenetServer - www.usenetserver.com
Date: Wed, 17 Nov 2021 15:34:34 GMT
X-Received-Bytes: 1152
 by: Scott Lurndal - Wed, 17 Nov 2021 15:34 UTC

pozz <pozzugno@gmail.com> writes:
>Many times I need to construct a string through a call to sprintf and
>pass it to an external function.
>
> char s[32];
> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
> lcd_write(s);

One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.

I generally always reserve enough space for the largest possible
legal string, particularly when the buffer is on the stack and is
less than a page (4KB) in size.

Re: Automatic strings without malloc

<24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19015&group=comp.lang.c#19015

  copy link   Newsgroups: comp.lang.c
X-Received: by 2002:a05:622a:1aa5:: with SMTP id s37mr17446518qtc.377.1637163414379;
Wed, 17 Nov 2021 07:36:54 -0800 (PST)
X-Received: by 2002:a37:8947:: with SMTP id l68mr14102062qkd.459.1637163414235;
Wed, 17 Nov 2021 07:36:54 -0800 (PST)
Path: i2pn2.org!i2pn.org!weretis.net!feeder6.news.weretis.net!news.misty.com!border2.nntp.dca1.giganews.com!nntp.giganews.com!news-out.google.com!nntp.google.com!postnews.google.com!google-groups.googlegroups.com!not-for-mail
Newsgroups: comp.lang.c
Date: Wed, 17 Nov 2021 07:36:54 -0800 (PST)
In-Reply-To: <ei9lJ.146291$I%1.54591@fx36.iad>
Injection-Info: google-groups.googlegroups.com; posting-host=2a00:23a8:400a:5601:b1ed:260c:3588:7d3b;
posting-account=Dz2zqgkAAADlK5MFu78bw3ab-BRFV4Qn
NNTP-Posting-Host: 2a00:23a8:400a:5601:b1ed:260c:3588:7d3b
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad>
User-Agent: G2/1.0
MIME-Version: 1.0
Message-ID: <24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com>
Subject: Re: Automatic strings without malloc
From: malcolm....@gmail.com (Malcolm McLean)
Injection-Date: Wed, 17 Nov 2021 15:36:54 +0000
Content-Type: text/plain; charset="UTF-8"
Lines: 10
 by: Malcolm McLean - Wed, 17 Nov 2021 15:36 UTC

On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
> pozz <pozz...@gmail.com> writes:
> >Many times I need to construct a string through a call to sprintf and
> >pass it to an external function.
> >
> > char s[32];
> > sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
> > lcd_write(s);
> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
>
It depends whether wrong results are better or worse than no results.

Re: Automatic strings without malloc

<sn38n4$l8i$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19016&group=comp.lang.c#19016

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: david.br...@hesbynett.no (David Brown)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Wed, 17 Nov 2021 16:56:20 +0100
Organization: A noiseless patient Spider
Lines: 18
Message-ID: <sn38n4$l8i$1@dont-email.me>
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad>
<24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit
Injection-Date: Wed, 17 Nov 2021 15:56:20 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="476d31386fcaa27dba3f738faf4e6e3a";
logging-data="21778"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/mr9XyZsAshb2QJT46aLpvLA9VLPICa78="
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101
Thunderbird/78.11.0
Cancel-Lock: sha1:Cl7x+0WfQyK+lW2+/M5lZfnErs4=
In-Reply-To: <24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com>
Content-Language: en-GB
 by: David Brown - Wed, 17 Nov 2021 15:56 UTC

On 17/11/2021 16:36, Malcolm McLean wrote:
> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
>> pozz <pozz...@gmail.com> writes:
>>> Many times I need to construct a string through a call to sprintf and
>>> pass it to an external function.
>>>
>>> char s[32];
>>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>> lcd_write(s);
>> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
>>
> It depends whether wrong results are better or worse than no results.
>

Generally, a truncated string on the output is better than a stack
overflow with your embedded system crashing or going wild. But your
needs may vary.

Re: Automatic strings without malloc

<sn3dim$1li1$1@gioia.aioe.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19017&group=comp.lang.c#19017

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!aioe.org!Puiiztk9lHEEQC0y3uUjRA.user.46.165.242.75.POSTED!not-for-mail
From: non...@add.invalid (Manfred)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Wed, 17 Nov 2021 18:19:18 +0100
Organization: Aioe.org NNTP Server
Message-ID: <sn3dim$1li1$1@gioia.aioe.org>
References: <sn2lvp$sl7$1@dont-email.me> <sn2nk2$7mp$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Info: gioia.aioe.org; logging-data="54849"; posting-host="Puiiztk9lHEEQC0y3uUjRA.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.3.1
X-Notice: Filtered by postfilter v. 0.9.2
Content-Language: en-US
 by: Manfred - Wed, 17 Nov 2021 17:19 UTC

On 11/17/2021 12:04 PM, David Brown wrote:
> On 17/11/2021 11:36, pozz wrote:
>> Many times I need to construct a string through a call to sprintf and
>> pass it to an external function.
>>
>>   char s[32];
>>   sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>   lcd_write(s);
>>
>> The size of s is fixed and calculated for the maximum length of
>> yourname, that is 9.
>>
>> Later in time, I need to change the message into:
>>
>>   sprintf(s, "Hello %s, today is %d/%d/%d", yourname, day, month, year);
>>
>> Of course, I need to re-calculate the worst-case length, that should be
>> now 35. However this is error-prone and I could forget to change the
>> size of array.
>>
>> Is there a better way to manage this situation? I can't use malloc()
>> because I'm on an embedded system where I can't use heap.
>>
>> I'm thinking to use sprintf(NULL, ...), such as:
>>
>>   const char fmt[] = "Hi %s, today is %d/%d/%d";
>>   size_t n = sprintf(NULL, fmt, yourname, day, month, year);
>>   char s[n + 1];
>>   sprintf(s, fmt, yourname, day, month, year);
>>   lcd_write(s);
>>
>
> That would work (with your follow-up correction). You might want to put
> a limit on "n" to avoid accidental stack overflow. This arrangement
> does mean that you are doing the printf part twice.
>
> Very often in small systems you know there is a maximum size - if your
> screen is 40 characters wide, then 40 characters is enough in your
> array. And if you might need up to 40 characters then you might as well
> use all of the 40 chars, even though your string might be shorter - you
> really don't want to test your code for the name "Al" on date 1/2/2021
> and then find you have a stack overflow on 10/10/2021 with the name
> "Rhoshandiatellyneshiaunneveshenk". (Apparently that's a real name -
> according to google!)

This sounds like good advice. It makes sense to make use of the
information given by the maximum string length that can actually be emitted.

I'd add the following:
1) use snprintf instead of sprintf; the former is explicitly designed to
handle the buffer size limit.
2) use a better format specifier instead of plain "%s" for the string
argument, e.g. "%2.12s"

Both of the above help preventing buffer overflow, which is something
you need to ensure it never happens.

Re: Automatic strings without malloc

<9LblJ.45928$SW5.10995@fx45.iad>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19018&group=comp.lang.c#19018

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!weretis.net!feeder8.news.weretis.net!newsreader4.netcologne.de!news.netcologne.de!peer02.ams1!peer.ams1.xlned.com!news.xlned.com!peer02.iad!feed-me.highwinds-media.com!news.highwinds-media.com!fx45.iad.POSTED!not-for-mail
X-newsreader: xrn 9.03-beta-14-64bit
Sender: scott@dragon.sl.home (Scott Lurndal)
From: sco...@slp53.sl.home (Scott Lurndal)
Reply-To: slp53@pacbell.net
Subject: Re: Automatic strings without malloc
Newsgroups: comp.lang.c
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad> <24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com> <sn38n4$l8i$1@dont-email.me>
Lines: 22
Message-ID: <9LblJ.45928$SW5.10995@fx45.iad>
X-Complaints-To: abuse@usenetserver.com
NNTP-Posting-Date: Wed, 17 Nov 2021 18:21:57 UTC
Organization: UsenetServer - www.usenetserver.com
Date: Wed, 17 Nov 2021 18:21:57 GMT
X-Received-Bytes: 1623
 by: Scott Lurndal - Wed, 17 Nov 2021 18:21 UTC

David Brown <david.brown@hesbynett.no> writes:
>On 17/11/2021 16:36, Malcolm McLean wrote:
>> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
>>> pozz <pozz...@gmail.com> writes:
>>>> Many times I need to construct a string through a call to sprintf and
>>>> pass it to an external function.
>>>>
>>>> char s[32];
>>>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>>> lcd_write(s);
>>> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
>>>
>> It depends whether wrong results are better or worse than no results.
>>
>
>Generally, a truncated string on the output is better than a stack
>overflow with your embedded system crashing or going wild. But your
>needs may vary.

Indeed. Plus a good programmer checks the return value from snprintf.
Always.

Re: Automatic strings without malloc

<87lf1mvbl5.fsf@nosuchdomain.example.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19019&group=comp.lang.c#19019

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: Keith.S....@gmail.com (Keith Thompson)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Wed, 17 Nov 2021 11:14:30 -0800
Organization: None to speak of
Lines: 15
Message-ID: <87lf1mvbl5.fsf@nosuchdomain.example.com>
References: <sn2lvp$sl7$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: reader02.eternal-september.org; posting-host="6adbb48cfacfb1ab527767c44a65f2ee";
logging-data="9314"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/pMrbr56NRaeSE2eWWEhhQ"
User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
Cancel-Lock: sha1:FSf/GSAjfc/K+h7a+CWu+8G9MDw=
sha1:JluURKiDjw0jRR6IkWriZpZh9r8=
 by: Keith Thompson - Wed, 17 Nov 2021 19:14 UTC

pozz <pozzugno@gmail.com> writes:
> Many times I need to construct a string through a call to sprintf and
> pass it to an external function.
>
> char s[32];
> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
> lcd_write(s);

I presume that lcd_write() doesn't retain the address passed to it, so the
display won't be messed up when the array object s ceases to exist.

--
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
Working, but not speaking, for Philips
void Void(void) { Void(); } /* The recursive call of the void */

Re: Automatic strings without malloc

<87tugapoxu.fsf@nosuchdomain.example.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19020&group=comp.lang.c#19020

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!weretis.net!feeder8.news.weretis.net!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: Keith.S....@gmail.com (Keith Thompson)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Wed, 17 Nov 2021 11:22:37 -0800
Organization: None to speak of
Lines: 34
Message-ID: <87tugapoxu.fsf@nosuchdomain.example.com>
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad>
<24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com>
<sn38n4$l8i$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: reader02.eternal-september.org; posting-host="6adbb48cfacfb1ab527767c44a65f2ee";
logging-data="18730"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18KoZ9Xl9FTSx079a/YuV9C"
User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
Cancel-Lock: sha1:bW2Gh8adSLFzngHL0QP7YqEYlxQ=
sha1:RZ2hK1YXBgfv6bUgdsN8H/NhNTA=
 by: Keith Thompson - Wed, 17 Nov 2021 19:22 UTC

David Brown <david.brown@hesbynett.no> writes:
> On 17/11/2021 16:36, Malcolm McLean wrote:
>> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
>>> pozz <pozz...@gmail.com> writes:
>>>> Many times I need to construct a string through a call to sprintf and
>>>> pass it to an external function.
>>>>
>>>> char s[32];
>>>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>>> lcd_write(s);
>>> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
>>>
>> It depends whether wrong results are better or worse than no results.
>
> Generally, a truncated string on the output is better than a stack
> overflow with your embedded system crashing or going wild. But your
> needs may vary.

Sure, truncation is probably better than undefined behavior, but
depending on the context it might not be *much* better.

For a small LCD display, truncation is probably the best fallback
(followed by thinking about how to make the message fit). On the other
hand, truncating "rm -rf /home/user/temp_dir" to "rm -rf /home/user" is
likely to be far worse than crashing the program.

There's no general rule other than that you should always *think*
about what will/should happen if there's not enough room in the target
array.

--
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
Working, but not speaking, for Philips
void Void(void) { Void(); } /* The recursive call of the void */

Re: Automatic strings without malloc

<sn3lgp$qhj$2@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19021&group=comp.lang.c#19021

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: david.br...@hesbynett.no (David Brown)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Wed, 17 Nov 2021 20:34:49 +0100
Organization: A noiseless patient Spider
Lines: 69
Message-ID: <sn3lgp$qhj$2@dont-email.me>
References: <sn2lvp$sl7$1@dont-email.me> <sn2nk2$7mp$1@dont-email.me>
<sn3dim$1li1$1@gioia.aioe.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
Injection-Date: Wed, 17 Nov 2021 19:34:49 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="35acc5cbdda1034c2803d0db3462263e";
logging-data="27187"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18k1t2dYrZPAMQeoq6t2ttyLalKE1LtvfU="
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101
Thunderbird/78.11.0
Cancel-Lock: sha1:hxmDRj7wkVsPrg9ROwIkg+wXDYc=
In-Reply-To: <sn3dim$1li1$1@gioia.aioe.org>
Content-Language: en-GB
 by: David Brown - Wed, 17 Nov 2021 19:34 UTC

On 17/11/2021 18:19, Manfred wrote:
> On 11/17/2021 12:04 PM, David Brown wrote:
>> On 17/11/2021 11:36, pozz wrote:
>>> Many times I need to construct a string through a call to sprintf and
>>> pass it to an external function.
>>>
>>>    char s[32];
>>>    sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>>    lcd_write(s);
>>>
>>> The size of s is fixed and calculated for the maximum length of
>>> yourname, that is 9.
>>>
>>> Later in time, I need to change the message into:
>>>
>>>    sprintf(s, "Hello %s, today is %d/%d/%d", yourname, day, month,
>>> year);
>>>
>>> Of course, I need to re-calculate the worst-case length, that should be
>>> now 35. However this is error-prone and I could forget to change the
>>> size of array.
>>>
>>> Is there a better way to manage this situation? I can't use malloc()
>>> because I'm on an embedded system where I can't use heap.
>>>
>>> I'm thinking to use sprintf(NULL, ...), such as:
>>>
>>>    const char fmt[] = "Hi %s, today is %d/%d/%d";
>>>    size_t n = sprintf(NULL, fmt, yourname, day, month, year);
>>>    char s[n + 1];
>>>    sprintf(s, fmt, yourname, day, month, year);
>>>    lcd_write(s);
>>>
>>
>> That would work (with your follow-up correction).  You might want to put
>> a limit on "n" to avoid accidental stack overflow.  This arrangement
>> does mean that you are doing the printf part twice.
>>
>> Very often in small systems you know there is a maximum size - if your
>> screen is 40 characters wide, then 40 characters is enough in your
>> array.  And if you might need up to 40 characters then you might as well
>> use all of the 40 chars, even though your string might be shorter - you
>> really don't want to test your code for the name "Al" on date 1/2/2021
>> and then find you have a stack overflow on 10/10/2021 with the name
>> "Rhoshandiatellyneshiaunneveshenk".  (Apparently that's a real name -
>> according to google!)
>
> This sounds like good advice. It makes sense to make use of the
> information given by the maximum string length that can actually be
> emitted.
>
> I'd add the following:
> 1) use snprintf instead of sprintf; the former is explicitly designed to
> handle the buffer size limit.

Of course. The OP corrected himself with a follow-up to use snprintf, I
believe.

> 2) use a better format specifier instead of plain "%s" for the string
> argument, e.g. "%2.12s"

That is a possibility, but often %s is fine (with the limit you have
from snprintf).

>
> Both of the above help preventing buffer overflow, which is something
> you need to ensure it never happens.

Indeed.

Re: Automatic strings without malloc

<sn3llm$qhj$3@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19022&group=comp.lang.c#19022

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: david.br...@hesbynett.no (David Brown)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Wed, 17 Nov 2021 20:37:26 +0100
Organization: A noiseless patient Spider
Lines: 31
Message-ID: <sn3llm$qhj$3@dont-email.me>
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad>
<24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com>
<sn38n4$l8i$1@dont-email.me> <9LblJ.45928$SW5.10995@fx45.iad>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit
Injection-Date: Wed, 17 Nov 2021 19:37:26 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="35acc5cbdda1034c2803d0db3462263e";
logging-data="27187"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19XWXcAKLGffCONC2WeAMtrYWIi/w7rB/U="
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101
Thunderbird/78.11.0
Cancel-Lock: sha1:19RGCHmsXosYaks7q1PjPGgUz3U=
In-Reply-To: <9LblJ.45928$SW5.10995@fx45.iad>
Content-Language: en-GB
 by: David Brown - Wed, 17 Nov 2021 19:37 UTC

On 17/11/2021 19:21, Scott Lurndal wrote:
> David Brown <david.brown@hesbynett.no> writes:
>> On 17/11/2021 16:36, Malcolm McLean wrote:
>>> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
>>>> pozz <pozz...@gmail.com> writes:
>>>>> Many times I need to construct a string through a call to sprintf and
>>>>> pass it to an external function.
>>>>>
>>>>> char s[32];
>>>>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>>>> lcd_write(s);
>>>> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
>>>>
>>> It depends whether wrong results are better or worse than no results.
>>>
>>
>> Generally, a truncated string on the output is better than a stack
>> overflow with your embedded system crashing or going wild. But your
>> needs may vary.
>
> Indeed. Plus a good programmer checks the return value from snprintf.
> Always.
>

Really? I never do. But I make sure my buffers are the right size for
the job - or that it doesn't matter if there is truncation (such as for
log outputs). I prefer to be sure that my inputs to the function are
correct, than to call the function and check for problems afterwards.
(Different people can have different requirements here - but that's the
way I do it.)

Re: Automatic strings without malloc

<sn3lq4$qhj$4@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19023&group=comp.lang.c#19023

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: david.br...@hesbynett.no (David Brown)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Wed, 17 Nov 2021 20:39:48 +0100
Organization: A noiseless patient Spider
Lines: 38
Message-ID: <sn3lq4$qhj$4@dont-email.me>
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad>
<24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com>
<sn38n4$l8i$1@dont-email.me> <87tugapoxu.fsf@nosuchdomain.example.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit
Injection-Date: Wed, 17 Nov 2021 19:39:48 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="35acc5cbdda1034c2803d0db3462263e";
logging-data="27187"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/b0xBTPqD6pCIpwnXGHwVvmf0LJBhcZW4="
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101
Thunderbird/78.11.0
Cancel-Lock: sha1:1PSlQaERr49SlabxPnCT/3qJnTw=
In-Reply-To: <87tugapoxu.fsf@nosuchdomain.example.com>
Content-Language: en-GB
 by: David Brown - Wed, 17 Nov 2021 19:39 UTC

On 17/11/2021 20:22, Keith Thompson wrote:
> David Brown <david.brown@hesbynett.no> writes:
>> On 17/11/2021 16:36, Malcolm McLean wrote:
>>> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
>>>> pozz <pozz...@gmail.com> writes:
>>>>> Many times I need to construct a string through a call to sprintf and
>>>>> pass it to an external function.
>>>>>
>>>>> char s[32];
>>>>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>>>> lcd_write(s);
>>>> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
>>>>
>>> It depends whether wrong results are better or worse than no results.
>>
>> Generally, a truncated string on the output is better than a stack
>> overflow with your embedded system crashing or going wild. But your
>> needs may vary.
>
> Sure, truncation is probably better than undefined behavior, but
> depending on the context it might not be *much* better.
>
> For a small LCD display, truncation is probably the best fallback
> (followed by thinking about how to make the message fit). On the other
> hand, truncating "rm -rf /home/user/temp_dir" to "rm -rf /home/user" is
> likely to be far worse than crashing the program.

Yes - "generally" does not mean "always" ! That's a good example of
when truncation could be rather bad.

>
> There's no general rule other than that you should always *think*
> about what will/should happen if there's not enough room in the target
> array.
>

Alternatively, think about how to ensure that there /always/ will be
enough room in the target array. Either way, always /think/.

Re: Automatic strings without malloc

<0BelJ.45864$np6.1851@fx46.iad>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19025&group=comp.lang.c#19025

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!paganini.bofh.team!news.dns-netz.com!news.freedyn.net!newsfeed.xs4all.nl!newsfeed8.news.xs4all.nl!news-out.netnews.com!news.alt.net!fdc2.netnews.com!peer01.ams1!peer.ams1.xlned.com!news.xlned.com!peer02.iad!feed-me.highwinds-media.com!news.highwinds-media.com!fx46.iad.POSTED!not-for-mail
X-newsreader: xrn 9.03-beta-14-64bit
Sender: scott@dragon.sl.home (Scott Lurndal)
From: sco...@slp53.sl.home (Scott Lurndal)
Reply-To: slp53@pacbell.net
Subject: Re: Automatic strings without malloc
Newsgroups: comp.lang.c
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad> <24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com> <sn38n4$l8i$1@dont-email.me> <9LblJ.45928$SW5.10995@fx45.iad> <sn3llm$qhj$3@dont-email.me>
Lines: 56
Message-ID: <0BelJ.45864$np6.1851@fx46.iad>
X-Complaints-To: abuse@usenetserver.com
NNTP-Posting-Date: Wed, 17 Nov 2021 21:35:56 UTC
Organization: UsenetServer - www.usenetserver.com
Date: Wed, 17 Nov 2021 21:35:56 GMT
X-Received-Bytes: 3014
 by: Scott Lurndal - Wed, 17 Nov 2021 21:35 UTC

David Brown <david.brown@hesbynett.no> writes:
>On 17/11/2021 19:21, Scott Lurndal wrote:
>> David Brown <david.brown@hesbynett.no> writes:
>>> On 17/11/2021 16:36, Malcolm McLean wrote:
>>>> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
>>>>> pozz <pozz...@gmail.com> writes:
>>>>>> Many times I need to construct a string through a call to sprintf and
>>>>>> pass it to an external function.
>>>>>>
>>>>>> char s[32];
>>>>>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>>>>> lcd_write(s);
>>>>> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
>>>>>
>>>> It depends whether wrong results are better or worse than no results.
>>>>
>>>
>>> Generally, a truncated string on the output is better than a stack
>>> overflow with your embedded system crashing or going wild. But your
>>> needs may vary.
>>
>> Indeed. Plus a good programmer checks the return value from snprintf.
>> Always.
>>
>
>Really? I never do. But I make sure my buffers are the right size for
>the job - or that it doesn't matter if there is truncation (such as for
>log outputs). I prefer to be sure that my inputs to the function are
>correct, than to call the function and check for problems afterwards.
>(Different people can have different requirements here - but that's the
>way I do it.)
>

I often use snprintf in place of strcat. For that purpose, checking the return
value is required.

char buffer[1024];
char *bp = buffer;
size_t remaining = sizeof(buffer);
int diag;

diag = snprintf(bp, remaining, "%s", string_to_append_to_buffer);
if (diag != -1 && diag < remaining) {
bp += diag, remaining -= diag;
} else {
/* Handle overflow/error as necessary */
}

....

The only problem is that the return value for snprintf is 'int', while
the buffer size is size_t; which means on systems with a 64-bit size_t,
the return value isn't large enough to express the correct return value
when the size of the result value exceeds 4GB. Not generally a problem in
actual code, but something to be aware of.

Re: Automatic strings without malloc

<87pmqype0g.fsf@nosuchdomain.example.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19027&group=comp.lang.c#19027

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: Keith.S....@gmail.com (Keith Thompson)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Wed, 17 Nov 2021 15:18:39 -0800
Organization: None to speak of
Lines: 49
Message-ID: <87pmqype0g.fsf@nosuchdomain.example.com>
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad>
<24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com>
<sn38n4$l8i$1@dont-email.me> <87tugapoxu.fsf@nosuchdomain.example.com>
<sn3lq4$qhj$4@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: reader02.eternal-september.org; posting-host="fa21211b32feab54b53731198dd84de4";
logging-data="28027"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18AnVN+uI933UWXscI/4Udr"
User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
Cancel-Lock: sha1:kdnSXl5r5f4lLucQlfrPShZwY88=
sha1:Uu05wliYNPYcn0V0ehJLE7c0VdQ=
 by: Keith Thompson - Wed, 17 Nov 2021 23:18 UTC

David Brown <david.brown@hesbynett.no> writes:
> On 17/11/2021 20:22, Keith Thompson wrote:
>> David Brown <david.brown@hesbynett.no> writes:
>>> On 17/11/2021 16:36, Malcolm McLean wrote:
>>>> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
>>>>> pozz <pozz...@gmail.com> writes:
>>>>>> Many times I need to construct a string through a call to sprintf and
>>>>>> pass it to an external function.
>>>>>>
>>>>>> char s[32];
>>>>>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>>>>> lcd_write(s);
>>>>> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
>>>>>
>>>> It depends whether wrong results are better or worse than no results.
>>>
>>> Generally, a truncated string on the output is better than a stack
>>> overflow with your embedded system crashing or going wild. But your
>>> needs may vary.
>>
>> Sure, truncation is probably better than undefined behavior, but
>> depending on the context it might not be *much* better.
>>
>> For a small LCD display, truncation is probably the best fallback
>> (followed by thinking about how to make the message fit). On the other
>> hand, truncating "rm -rf /home/user/temp_dir" to "rm -rf /home/user" is
>> likely to be far worse than crashing the program.
>
> Yes - "generally" does not mean "always" ! That's a good example of
> when truncation could be rather bad.

Depending on the context, "generally" can mean either "usually" or
"always". I've found that people generally interpret it in the most
inconvenient way possible.

>> There's no general rule other than that you should always *think*
>> about what will/should happen if there's not enough room in the target
>> array.
>
> Alternatively, think about how to ensure that there /always/ will be
> enough room in the target array. Either way, always /think/.

That's not always possible, especially if the "array" is a display
device. But yes, "always think" is a good idea. I think.

--
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
Working, but not speaking, for Philips
void Void(void) { Void(); } /* The recursive call of the void */

Re: Automatic strings without malloc

<pd2h6i-dsm1.ln1@wilbur.25thandClement.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19029&group=comp.lang.c#19029

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!weretis.net!feeder6.news.weretis.net!news.misty.com!border2.nntp.dca1.giganews.com!nntp.giganews.com!buffer2.nntp.dca1.giganews.com!news.giganews.com.POSTED!not-for-mail
NNTP-Posting-Date: Wed, 17 Nov 2021 23:00:01 -0600
Message-ID: <pd2h6i-dsm1.ln1@wilbur.25thandClement.com>
From: will...@25thandClement.com (William Ahern)
Subject: Re: Automatic strings without malloc
Newsgroups: comp.lang.c
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad> <24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com> <sn38n4$l8i$1@dont-email.me> <9LblJ.45928$SW5.10995@fx45.iad> <sn3llm$qhj$3@dont-email.me>
User-Agent: tin/2.4.4-20191224 ("Millburn") (OpenBSD/6.9 (amd64))
Date: Wed, 17 Nov 2021 20:46:17 -0800
Lines: 45
X-Usenet-Provider: http://www.giganews.com
X-Trace: sv3-mughpLrD7f9Jvwdn+zHteol70Dk3epIleYcUZIlziimuN5DJA97B8nqL7AoB+KTmEoWUyZkEL7Vz5WK!ULm1qtoceUooPm3m1FSWWOJtEfk8SNKUOBuvUbUWiJCmomFDmex368YXF+r5iWQ2Ups=
X-Complaints-To: abuse@giganews.com
X-DMCA-Notifications: http://www.giganews.com/info/dmca.html
X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers
X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly
X-Postfilter: 1.3.40
X-Original-Bytes: 3348
 by: William Ahern - Thu, 18 Nov 2021 04:46 UTC

David Brown <david.brown@hesbynett.no> wrote:
> On 17/11/2021 19:21, Scott Lurndal wrote:
>> David Brown <david.brown@hesbynett.no> writes:
>>> On 17/11/2021 16:36, Malcolm McLean wrote:
>>>> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
>>>>> pozz <pozz...@gmail.com> writes:
>>>>>> Many times I need to construct a string through a call to sprintf and
>>>>>> pass it to an external function.
>>>>>>
>>>>>> char s[32];
>>>>>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>>>>> lcd_write(s);
>>>>> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
>>>>>
>>>> It depends whether wrong results are better or worse than no results.
>>>>
>>>
>>> Generally, a truncated string on the output is better than a stack
>>> overflow with your embedded system crashing or going wild. But your
>>> needs may vary.
>>
>> Indeed. Plus a good programmer checks the return value from snprintf.
>> Always.
>>
>
> Really? I never do. But I make sure my buffers are the right size for
> the job - or that it doesn't matter if there is truncation (such as for
> log outputs). I prefer to be sure that my inputs to the function are
> correct, than to call the function and check for problems afterwards.
> (Different people can have different requirements here - but that's the
> way I do it.)
>

That is generally the best approach, but doesn't work well with snprintf (or
stringification of data types generally), especially in light of the express
concern about robustness to drive-by edits of the format string.

The way to avoid string buffer errors is to avoid strings and stick to
concrete data types or to process data in a rigorously streaming fashion.
That's true of C and other languages--strings aren't data structures,
they're the antithesis of a data structure. But one nonetheless often finds
themselves dealing with strings either on input or output, unfortunately,
and facing the cruel economic calculus of worse is better. Which I suppose
is why every language spends so much effort chasing a better string type
despite the very phrase, string type, being a contradiction in terms.

Re: Automatic strings without malloc

<sn555a$cjo$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19031&group=comp.lang.c#19031

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: pozzu...@gmail.com (pozz)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Thu, 18 Nov 2021 10:07:54 +0100
Organization: A noiseless patient Spider
Lines: 61
Message-ID: <sn555a$cjo$1@dont-email.me>
References: <sn2lvp$sl7$1@dont-email.me> <sn2nk2$7mp$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Date: Thu, 18 Nov 2021 09:07:54 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="3d829fb3e17ff69060ac30b30f2cf54e";
logging-data="12920"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1//jaMd5jYCX220eQQEM59/UPYewDJO/F0="
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.3.1
Cancel-Lock: sha1:U850g5qE37r4Z2eD48CCEyhFSg0=
In-Reply-To: <sn2nk2$7mp$1@dont-email.me>
 by: pozz - Thu, 18 Nov 2021 09:07 UTC

Il 17/11/2021 12:04, David Brown ha scritto:
> On 17/11/2021 11:36, pozz wrote:
>> Many times I need to construct a string through a call to sprintf and
>> pass it to an external function.
>>
>>   char s[32];
>>   sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>   lcd_write(s);
>>
>> The size of s is fixed and calculated for the maximum length of
>> yourname, that is 9.
>>
>> Later in time, I need to change the message into:
>>
>>   sprintf(s, "Hello %s, today is %d/%d/%d", yourname, day, month, year);
>>
>> Of course, I need to re-calculate the worst-case length, that should be
>> now 35. However this is error-prone and I could forget to change the
>> size of array.
>>
>> Is there a better way to manage this situation? I can't use malloc()
>> because I'm on an embedded system where I can't use heap.
>>
>> I'm thinking to use sprintf(NULL, ...), such as:
>>
>>   const char fmt[] = "Hi %s, today is %d/%d/%d";
>>   size_t n = sprintf(NULL, fmt, yourname, day, month, year);
>>   char s[n + 1];
>>   sprintf(s, fmt, yourname, day, month, year);
>>   lcd_write(s);
>>
>
> That would work (with your follow-up correction). You might want to put
> a limit on "n" to avoid accidental stack overflow. This arrangement
> does mean that you are doing the printf part twice.

I know, this is a drawback.

> Very often in small systems you know there is a maximum size - if your
> screen is 40 characters wide, then 40 characters is enough in your
> array. And if you might need up to 40 characters then you might as well
> use all of the 40 chars, even though your string might be shorter - you
> really don't want to test your code for the name "Al" on date 1/2/2021
> and then find you have a stack overflow on 10/10/2021 with the name
> "Rhoshandiatellyneshiaunneveshenk". (Apparently that's a real name -
> according to google!)

The example was general, because this is a problem I often have: compose
a string now to pass to a function.

For LCD example, if you use a variable-width font, it's difficult to
calc the maximum chars. It depends how many 'i's are in the string.
You could consider the worst case of a string composed by all 'i's...

> It is also worth noting that only one task should be calling lcd_write
> at a time - otherwise your display will be messed up. You can extend
> that and say that only one task will be using the format buffer at a
> time, and then it can be a statically array that is shared by all client
> code.

Re: Automatic strings without malloc

<sn555j$cjo$2@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19032&group=comp.lang.c#19032

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: pozzu...@gmail.com (pozz)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Thu, 18 Nov 2021 10:08:03 +0100
Organization: A noiseless patient Spider
Lines: 14
Message-ID: <sn555j$cjo$2@dont-email.me>
References: <sn2lvp$sl7$1@dont-email.me>
<87lf1mvbl5.fsf@nosuchdomain.example.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Thu, 18 Nov 2021 09:08:03 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="3d829fb3e17ff69060ac30b30f2cf54e";
logging-data="12920"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19lkikXEjF6p9M/JWQSsqeXZgrF2y/kckg="
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.3.1
Cancel-Lock: sha1:hfDJQyYzCNKRQv/3x+ZG8aUT7cQ=
In-Reply-To: <87lf1mvbl5.fsf@nosuchdomain.example.com>
 by: pozz - Thu, 18 Nov 2021 09:08 UTC

Il 17/11/2021 20:14, Keith Thompson ha scritto:
> pozz <pozzugno@gmail.com> writes:
>> Many times I need to construct a string through a call to sprintf and
>> pass it to an external function.
>>
>> char s[32];
>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>> lcd_write(s);
>
> I presume that lcd_write() doesn't retain the address passed to it, so the
> display won't be messed up when the array object s ceases to exist.

Yes of course

Re: Automatic strings without malloc

<sn57ku$tea$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19033&group=comp.lang.c#19033

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: david.br...@hesbynett.no (David Brown)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Thu, 18 Nov 2021 10:50:22 +0100
Organization: A noiseless patient Spider
Lines: 66
Message-ID: <sn57ku$tea$1@dont-email.me>
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad>
<24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com>
<sn38n4$l8i$1@dont-email.me> <9LblJ.45928$SW5.10995@fx45.iad>
<sn3llm$qhj$3@dont-email.me> <pd2h6i-dsm1.ln1@wilbur.25thandClement.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit
Injection-Date: Thu, 18 Nov 2021 09:50:22 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="eacba1fa919d2d9944baf4e35984ee78";
logging-data="30154"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+FCeqzR5frPifEKmo+zYcvYeuwhp/EbAc="
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101
Thunderbird/78.11.0
Cancel-Lock: sha1:1IBTkG+DjWOWAQ2n343X1AP5x6k=
In-Reply-To: <pd2h6i-dsm1.ln1@wilbur.25thandClement.com>
Content-Language: en-GB
 by: David Brown - Thu, 18 Nov 2021 09:50 UTC

On 18/11/2021 05:46, William Ahern wrote:
> David Brown <david.brown@hesbynett.no> wrote:
>> On 17/11/2021 19:21, Scott Lurndal wrote:
>>> David Brown <david.brown@hesbynett.no> writes:
>>>> On 17/11/2021 16:36, Malcolm McLean wrote:
>>>>> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
>>>>>> pozz <pozz...@gmail.com> writes:
>>>>>>> Many times I need to construct a string through a call to sprintf and
>>>>>>> pass it to an external function.
>>>>>>>
>>>>>>> char s[32];
>>>>>>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
>>>>>>> lcd_write(s);
>>>>>> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
>>>>>>
>>>>> It depends whether wrong results are better or worse than no results.
>>>>>
>>>>
>>>> Generally, a truncated string on the output is better than a stack
>>>> overflow with your embedded system crashing or going wild. But your
>>>> needs may vary.
>>>
>>> Indeed. Plus a good programmer checks the return value from snprintf.
>>> Always.
>>>
>>
>> Really? I never do. But I make sure my buffers are the right size for
>> the job - or that it doesn't matter if there is truncation (such as for
>> log outputs). I prefer to be sure that my inputs to the function are
>> correct, than to call the function and check for problems afterwards.
>> (Different people can have different requirements here - but that's the
>> way I do it.)
>>
>
> That is generally the best approach, but doesn't work well with snprintf (or
> stringification of data types generally), especially in light of the express
> concern about robustness to drive-by edits of the format string.
>

It works perfectly well in the type of programming I do. Different
kinds of work have different requirements. In small-systems embedded
programming (which is what I usually work with, and also what the OP is
doing), you know what you are passing to your printf type functions.
You know what the output is connected to (a screen, a UART, a log in
flash, etc.).

But it can be an entirely different matter in other kinds of programming
where you might have the format string coming from an external file of
translations made by a third party, or the endless variety of
complicating factors that can occur on big systems. Scott could be
right that a good programmer always checks the return value of snprintf
when doing the kind of coding he does - but it is not right for the kind
of coding /I/ do.

> The way to avoid string buffer errors is to avoid strings and stick to
> concrete data types or to process data in a rigorously streaming fashion.

The way to avoid string buffer errors is the same as you avoid any other
errors - good development practices. That runs the whole gamut from
high level concerns to low-level details. It includes making sure you
have clear specifications for the code you are writing, making sure the
programmer is appropriately qualified, having code review practices,
testing regimes, automatic checking tools, making sure the data coming
into your code is appropriate, making sure you correctly handle all
cases (including worst cases and pathological cases), and so on. It's
just like any other coding error.

Re: Automatic strings without malloc

<20b9b695-32b8-4361-b88a-38d041950994n@googlegroups.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19035&group=comp.lang.c#19035

  copy link   Newsgroups: comp.lang.c
X-Received: by 2002:a05:622a:38d:: with SMTP id j13mr25075588qtx.159.1637236618070;
Thu, 18 Nov 2021 03:56:58 -0800 (PST)
X-Received: by 2002:a05:6214:1c86:: with SMTP id ib6mr63304824qvb.26.1637236617936;
Thu, 18 Nov 2021 03:56:57 -0800 (PST)
Path: i2pn2.org!i2pn.org!weretis.net!feeder6.news.weretis.net!news.misty.com!border2.nntp.dca1.giganews.com!nntp.giganews.com!news-out.google.com!nntp.google.com!postnews.google.com!google-groups.googlegroups.com!not-for-mail
Newsgroups: comp.lang.c
Date: Thu, 18 Nov 2021 03:56:57 -0800 (PST)
In-Reply-To: <sn57ku$tea$1@dont-email.me>
Injection-Info: google-groups.googlegroups.com; posting-host=2a00:23a8:400a:5601:c089:97d0:7daa:10d4;
posting-account=Dz2zqgkAAADlK5MFu78bw3ab-BRFV4Qn
NNTP-Posting-Host: 2a00:23a8:400a:5601:c089:97d0:7daa:10d4
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad>
<24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com> <sn38n4$l8i$1@dont-email.me>
<9LblJ.45928$SW5.10995@fx45.iad> <sn3llm$qhj$3@dont-email.me>
<pd2h6i-dsm1.ln1@wilbur.25thandClement.com> <sn57ku$tea$1@dont-email.me>
User-Agent: G2/1.0
MIME-Version: 1.0
Message-ID: <20b9b695-32b8-4361-b88a-38d041950994n@googlegroups.com>
Subject: Re: Automatic strings without malloc
From: malcolm....@gmail.com (Malcolm McLean)
Injection-Date: Thu, 18 Nov 2021 11:56:58 +0000
Content-Type: text/plain; charset="UTF-8"
Lines: 75
 by: Malcolm McLean - Thu, 18 Nov 2021 11:56 UTC

On Thursday, 18 November 2021 at 09:50:36 UTC, David Brown wrote:
> On 18/11/2021 05:46, William Ahern wrote:
> > David Brown <david...@hesbynett.no> wrote:
> >> On 17/11/2021 19:21, Scott Lurndal wrote:
> >>> David Brown <david...@hesbynett.no> writes:
> >>>> On 17/11/2021 16:36, Malcolm McLean wrote:
> >>>>> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
> >>>>>> pozz <pozz...@gmail.com> writes:
> >>>>>>> Many times I need to construct a string through a call to sprintf and
> >>>>>>> pass it to an external function.
> >>>>>>>
> >>>>>>> char s[32];
> >>>>>>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
> >>>>>>> lcd_write(s);
> >>>>>> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
> >>>>>>
> >>>>> It depends whether wrong results are better or worse than no results.
> >>>>>
> >>>>
> >>>> Generally, a truncated string on the output is better than a stack
> >>>> overflow with your embedded system crashing or going wild. But your
> >>>> needs may vary.
> >>>
> >>> Indeed. Plus a good programmer checks the return value from snprintf.
> >>> Always.
> >>>
> >>
> >> Really? I never do. But I make sure my buffers are the right size for
> >> the job - or that it doesn't matter if there is truncation (such as for
> >> log outputs). I prefer to be sure that my inputs to the function are
> >> correct, than to call the function and check for problems afterwards.
> >> (Different people can have different requirements here - but that's the
> >> way I do it.)
> >>
> >
> > That is generally the best approach, but doesn't work well with snprintf (or
> > stringification of data types generally), especially in light of the express
> > concern about robustness to drive-by edits of the format string.
> >
> It works perfectly well in the type of programming I do. Different
> kinds of work have different requirements. In small-systems embedded
> programming (which is what I usually work with, and also what the OP is
> doing), you know what you are passing to your printf type functions.
> You know what the output is connected to (a screen, a UART, a log in
> flash, etc.).
>
> But it can be an entirely different matter in other kinds of programming
> where you might have the format string coming from an external file of
> translations made by a third party, or the endless variety of
> complicating factors that can occur on big systems. Scott could be
> right that a good programmer always checks the return value of snprintf
> when doing the kind of coding he does - but it is not right for the kind
> of coding /I/ do.
>
I tend to use C++ for strings because C++ strings are assignable, destructible,
returnable, and C++ manages the buffer. C isn't a good language for doing
string processing in (though it is a good language for implementing string
processing algorithms themselves in).
>
> > The way to avoid string buffer errors is to avoid strings and stick to
> > concrete data types or to process data in a rigorously streaming fashion.
> The way to avoid string buffer errors is the same as you avoid any other
> errors - good development practices. That runs the whole gamut from
> high level concerns to low-level details. It includes making sure you
> have clear specifications for the code you are writing, making sure the
> programmer is appropriately qualified, having code review practices,
> testing regimes, automatic checking tools, making sure the data coming
> into your code is appropriate, making sure you correctly handle all
> cases (including worst cases and pathological cases), and so on. It's
> just like any other coding error.
>
This all costs money, it demands management skills and resources
the company may not have, and it can lead to programmers feeling
over-managed.
A very important factor is the testability of the code, and the consequences
of an error. You can over-engineer processes as well as actual code.

Re: Automatic strings without malloc

<3b101498-3f74-4089-86ba-7ae728824e3en@googlegroups.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19036&group=comp.lang.c#19036

  copy link   Newsgroups: comp.lang.c
X-Received: by 2002:a05:6214:5186:: with SMTP id kl6mr63659519qvb.33.1637243662749;
Thu, 18 Nov 2021 05:54:22 -0800 (PST)
X-Received: by 2002:a05:620a:1659:: with SMTP id c25mr21246234qko.213.1637243662463;
Thu, 18 Nov 2021 05:54:22 -0800 (PST)
Path: i2pn2.org!i2pn.org!weretis.net!feeder6.news.weretis.net!news.misty.com!border2.nntp.dca1.giganews.com!nntp.giganews.com!news-out.google.com!nntp.google.com!postnews.google.com!google-groups.googlegroups.com!not-for-mail
Newsgroups: comp.lang.c
Date: Thu, 18 Nov 2021 05:54:22 -0800 (PST)
In-Reply-To: <20b9b695-32b8-4361-b88a-38d041950994n@googlegroups.com>
Injection-Info: google-groups.googlegroups.com; posting-host=189.6.249.78; posting-account=xFcAQAoAAAAoWlfpQ6Hz2n-MU9fthxbY
NNTP-Posting-Host: 189.6.249.78
References: <sn2lvp$sl7$1@dont-email.me> <ei9lJ.146291$I%1.54591@fx36.iad>
<24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com> <sn38n4$l8i$1@dont-email.me>
<9LblJ.45928$SW5.10995@fx45.iad> <sn3llm$qhj$3@dont-email.me>
<pd2h6i-dsm1.ln1@wilbur.25thandClement.com> <sn57ku$tea$1@dont-email.me> <20b9b695-32b8-4361-b88a-38d041950994n@googlegroups.com>
User-Agent: G2/1.0
MIME-Version: 1.0
Message-ID: <3b101498-3f74-4089-86ba-7ae728824e3en@googlegroups.com>
Subject: Re: Automatic strings without malloc
From: thiago.a...@gmail.com (Thiago Adams)
Injection-Date: Thu, 18 Nov 2021 13:54:22 +0000
Content-Type: text/plain; charset="UTF-8"
Lines: 105
 by: Thiago Adams - Thu, 18 Nov 2021 13:54 UTC

On Thursday, November 18, 2021 at 8:57:04 AM UTC-3, Malcolm McLean wrote:
> On Thursday, 18 November 2021 at 09:50:36 UTC, David Brown wrote:
> > On 18/11/2021 05:46, William Ahern wrote:
> > > David Brown <david...@hesbynett.no> wrote:
> > >> On 17/11/2021 19:21, Scott Lurndal wrote:
> > >>> David Brown <david...@hesbynett.no> writes:
> > >>>> On 17/11/2021 16:36, Malcolm McLean wrote:
> > >>>>> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote:
> > >>>>>> pozz <pozz...@gmail.com> writes:
> > >>>>>>> Many times I need to construct a string through a call to sprintf and
> > >>>>>>> pass it to an external function.
> > >>>>>>>
> > >>>>>>> char s[32];
> > >>>>>>> sprintf(s, "Hi %s, today is %d/%d/%d", yourname, day, month, year);
> > >>>>>>> lcd_write(s);
> > >>>>>> One might consider using 'snprintf' instead of 'sprintf'; it is a bit safer.
> > >>>>>>
> > >>>>> It depends whether wrong results are better or worse than no results.
> > >>>>>
> > >>>>
> > >>>> Generally, a truncated string on the output is better than a stack
> > >>>> overflow with your embedded system crashing or going wild. But your
> > >>>> needs may vary.
> > >>>
> > >>> Indeed. Plus a good programmer checks the return value from snprintf.
> > >>> Always.
> > >>>
> > >>
> > >> Really? I never do. But I make sure my buffers are the right size for
> > >> the job - or that it doesn't matter if there is truncation (such as for
> > >> log outputs). I prefer to be sure that my inputs to the function are
> > >> correct, than to call the function and check for problems afterwards.
> > >> (Different people can have different requirements here - but that's the
> > >> way I do it.)
> > >>
> > >
> > > That is generally the best approach, but doesn't work well with snprintf (or
> > > stringification of data types generally), especially in light of the express
> > > concern about robustness to drive-by edits of the format string.
> > >
> > It works perfectly well in the type of programming I do. Different
> > kinds of work have different requirements. In small-systems embedded
> > programming (which is what I usually work with, and also what the OP is
> > doing), you know what you are passing to your printf type functions.
> > You know what the output is connected to (a screen, a UART, a log in
> > flash, etc.).
> >
> > But it can be an entirely different matter in other kinds of programming
> > where you might have the format string coming from an external file of
> > translations made by a third party, or the endless variety of
> > complicating factors that can occur on big systems. Scott could be
> > right that a good programmer always checks the return value of snprintf
> > when doing the kind of coding he does - but it is not right for the kind
> > of coding /I/ do.
> >
> I tend to use C++ for strings because C++ strings are assignable, destructible,
> returnable, and C++ manages the buffer. C isn't a good language for doing
> string processing in (though it is a good language for implementing string
> processing algorithms themselves in).

I moved from C++ to C and I don't miss std::string. Quite the opposite, I don't feel
comfortable using std::string/std::wstring anymore even in C++.

One problem of std::string tries to do two different jobs at the same time
using the same object. One job is "string builder" and a the other "string holder"

Using std::string as string holder is a waste of memory. For instance:
std::map<std::string, something>
Map doesn't want build string, it just need to hold a string.

Another bad thing about std::string is to have to use .c_str() to make
it compatible with C strings. Clearly std::string is not a built-in
language string. "literals" are not std::string.

void F1(std::string s);
void F2(const std::string& s);
F("this is very bad because heap is used");
F("this is also very bad heap is used");

I have being using std::wstring for a long time. When moving to C
everything in my code is char* and it means UTF8. Life is so much
easier with much less conversions. It is amazing how few function we
need to work with UTF8. The same existing function can be used.
For instance, strcat is fine, strlen (if you need byte len), strdup etc.. everything just works.
u8"utf encoded" also completes the task.

What is missing. Because I create windows programs I miss the open_memstream.
This is for the job of "build strings" and to use the same FILE* functions.

So in C:
const char * or char * to represent and hold strings.
snprintf and open_memstream to build (and format) strings.

Dangerous parts...

strncpy because may not add NULL. ( I have heart of strlcpy )

replacement .
object->text = strdup("new text"); //this may cause a leak

especially for this replacement problem I think C++ has an advantage.

Something I use this that free the previous string.
replace_string(&object->text, strdup("new text"));

Re: Automatic strings without malloc

<sn5o0j$f35$1@solani.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19037&group=comp.lang.c#19037

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!weretis.net!feeder8.news.weretis.net!reader5.news.weretis.net!news.solani.org!.POSTED!not-for-mail
From: pkk...@spth.de (Philipp Klaus Krause)
Newsgroups: comp.lang.c
Subject: Re: Automatic strings without malloc
Date: Thu, 18 Nov 2021 15:29:39 +0100
Message-ID: <sn5o0j$f35$1@solani.org>
References: <sn2lvp$sl7$1@dont-email.me>
<8ae929dc-6b89-4a30-bbb0-16ceaeb94c63n@googlegroups.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit
Injection-Date: Thu, 18 Nov 2021 14:29:39 -0000 (UTC)
Injection-Info: solani.org;
logging-data="15461"; mail-complaints-to="abuse@news.solani.org"
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101
Thunderbird/78.14.0
Cancel-Lock: sha1:h2SvM0OZR+LNXZlXdNGsvDf5cBs=
Content-Language: en-US
In-Reply-To: <8ae929dc-6b89-4a30-bbb0-16ceaeb94c63n@googlegroups.com>
X-User-ID: eJwFwQkBwDAIA0BLfGGdHCjEv4TewVPzfpHIAEGDKFyiNt21BL1qfWl9dAINHtshuVO/KB8NsBF3
 by: Philipp Klaus Krause - Thu, 18 Nov 2021 14:29 UTC

Am 17.11.21 um 14:11 schrieb Thiago Adams:
>
> See : asprintf
> http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1248.pdf

asprintf allocates on the heap "as if by malloc", so if he can't use
malloc, he can't use asprintf.

Pages:12
server_pubkey.txt

rocksolid light 0.9.8
clearnet tor