Implementing a string copy function in C

前端 未结 9 1893
谎友^
谎友^ 2020-12-20 00:57

At a recent job interview, I was asked to implement my own string copy function. I managed to write code that I believe works to an extent. However, when I returned home to

9条回答
  •  没有蜡笔的小新
    2020-12-20 01:23

    Good interview question has several layers, to which to candidate can demonstrate different levels of understanding.

    On the syntactic 'C language' layer, the following code is from the classic Kernighan and Ritchie book ('The C programming language'):

    while( *dest++ = *src++ )
        ;
    

    In an interview, you could indeed point out the function isn't safe, most notably the buffer on *dest isn't large enough. Also, there may be overlap, i.e. if dest points to the middle of the src buffer, you'll have endless loop (which will eventually creates memory access fault).

提交回复
热议问题