Dealing with char buffers

前端 未结 9 1640
情书的邮戳
情书的邮戳 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:17

    You have a lot of questions! I'll do my best to answer a couple and give you a place to look for the others.

    Is there a maximum size that is considered safe for stack allocated buffers?

    Yes, but the stack size itself varies based on the platform you are working on. See When do you worry about stack size? for a very similar question.

    Is static char buffer[N]; faster? Are there any other arguments for or against it?

    The meaning of static is dependent on where the buffer is declared, but I assume you are talking about a static declared inside a function, so it is initialized only once. In functions called many times, using static buffers may be a good idea to prevent stack overflow, but otherwise, keep in mind that allocating buffers is a cheap operation. Also, static buffers are much harder to work with when dealing with multiple threads.

    For answers to most of your other questions, see Large buffers vs Large static buffers, is there an advantage?.

提交回复
热议问题