strcat segmentation fault

前端 未结 7 1823
后悔当初
后悔当初 2021-01-24 01:50

The second call to strcat here is generating a segmentation fault, why?

#include 
#include
#include 

        
7条回答
  •  梦毁少年i
    2021-01-24 01:59

    "String concatenation" is an idiom you should drop when learning C. Not only does it lead to a lot of bugs with overflowing buffers; it's also super inefficient. In your code, you could just have included the space in the snprintf format string (you should be using it in place of sprintf).

    Whenever possible, try to assemble a string entirely in one step using snprintf. This consolidates all of the buffer length checking into one place and makes it really hard to get wrong. You can also call snprintf with a 0 size argument to get the length that the combined string would be, in order to find out what size to allocate, if the size of the output is not known in advance (you should allocate one more byte than this length so that the null terminator does not truncate your output).

提交回复
热议问题