Determining sprintf buffer size - what's the standard?

前端 未结 7 1903
臣服心动
臣服心动 2020-11-28 06:51

When converting an int like so:

char a[256];
sprintf(a, \"%d\", 132);

what\'s the best way to determine how large a should be? I a

7条回答
  •  佛祖请我去吃肉
    2020-11-28 07:29

    First off, sprintf is the devil. If anything, use snprintf, or else you risk trashing memory and crashing your app.

    As for the buffer size, it's like all other buffers - as small as possible, as big as necessary. In your case, you have a signed integer, so take the largest possible size, and feel free to add a little bit of safety padding. There is no "standard size".

    It's also not dependent on what system you're running on. If you define the buffer on the stack (like in your example), it depends on the size of the stack. If you created the thread yourself, then you determined the stack size yourself, so you know the limits. If you are going to expect recursion or a deep stack trace, then you need to extra careful as well.

提交回复
热议问题