Path: csiph.com!newsfeed.xs4all.nl!newsfeed7.news.xs4all.nl!3.eu.feeder.erje.net!feeder.erje.net!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail From: 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: <24d7df90-3564-407a-999f-a33e774897c5n@googlegroups.com> 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= Xref: csiph.com comp.lang.c:163451 David Brown writes: > On 17/11/2021 16:36, Malcolm McLean wrote: >> On Wednesday, 17 November 2021 at 15:34:50 UTC, Scott Lurndal wrote: >>> pozz 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 */