Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!uunet!mcsun!unido!mikros!mwtech!martin From: martin@mwtech.UUCP (Martin Weitzel) Newsgroups: comp.lang.c Subject: Re: space allocation for sprintf() Message-ID: <1167@mwtech.UUCP> Date: 7 Jun 91 10:11:15 GMT References: <1991Jun5.174543.266@dg-rtp.dg.com> <1991Jun6.162723.27307@zoo.toronto.edu> Reply-To: martin@mwtech.UUCP (Martin Weitzel) Organization: MIKROS Systemware, Darmstadt/W-Germany Lines: 46 In article <1991Jun5.174543.266@dg-rtp.dg.com> vook@narnia.rtp.dg.com (Eric R Vook) writes: >"(It is the programmer's responsibility to ensure that the destination > string area is large enough to contain the output generated by the > formatting operation.)" > > How do you know how much space to allocate? > How do you know when you didn't allocate enough? In article <1991Jun6.162723.27307@zoo.toronto.edu> henry@zoo.toronto.edu (Henry Spencer) answers: >The fast answers are "you have to know how sprintf is being used and figure >out the longest string your parameters can result in" and "basically, you >don't". This is also my standard answer and I generally avoid using sprintf if I can't reliably calculate the required size of the buffer. But since I know that there are some outthere who will continue to use sprintf also when the buffer size couldn't be reliably determined, I have a suggestion (which may also help to check your calculations if you *think* you made the buffer large enough). If you are too lazy to follow Chris Toreks complete solution to the problem, at least write your code as follows: ********* NOTE THAT THIS DOESN'T GUARANTEE TO CATCH ALL PROBLEMS ********* ********* ON ANY MACHINE WHEN WRITING PAST THE END OF THE BUFFER! ********* #define MAX 40 /* if you think that 40 is enough */ char buffer[MAX+1]; buffer[MAX] = '\0'; sprintf(buffer, ......); if (buffer[MAX] != '\0') abort(); ********* NOTE THAT THIS DOESN'T GUARANTEE TO CATCH ALL PROBLEMS ********* ********* ON ANY MACHINE WHEN WRITING PAST THE END OF THE BUFFER! ********* But in general it's better than nothing, as on many architectures you will first overwrite other local variables and possibly the stack frame, then parameters of the function which contains this code and then locals, stack frames, and parameters of the calling functions. If your function never returns nor uses any other locals you have a good chance to at least detect the problem immediately. ********* NOTE THAT THIS DOESN'T GUARANTEE TO CATCH ALL PROBLEMS ********* ********* ON ANY MACHINE WHEN WRITING PAST THE END OF THE BUFFER! ********* -- Martin Weitzel, email: martin@mwtech.UUCP, voice: 49-(0)6151-6 56 83