Dealing with char buffers

前端 未结 9 1549
情书的邮戳
情书的邮戳 2021-02-08 02:33

As a C++ programmer I sometimes need deal with memory buffers using techniques from C. For example:

char buffer[512];
sprintf(buffer, \"Hello %s!\", userName.c_s         


        
9条回答
  •  春和景丽
    2021-02-08 03:03

    1. Stay away from static buffers if you ever want to use your code re-entrantly.

    2. use snprintf() instead of sprintf() so you can control buffer overruns.

    3. You never know how much stack space is left in the context of your call -- so no size is technically 'safe'. You have a lot of headroom to play with most of the time. But that one time will get you good. I use a rule of thumb to never put arrays on the stack.

    4. Have the client own the buffer and pass it and its size to your function. That makes it re-entrant and leaves no ambiguity as to who needs to manage the life of the buffer.

    5. If you're dealing with string data, double check your string functions to make sure they terminate especially when they hit the end of the buffer. The C library is very inconsistent when it comes to handling string termination across the various functions.

提交回复
热议问题