Implementing a string copy function in C

前端 未结 9 1830
谎友^
谎友^ 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:45

    No, you're writing past the buffer and overwriting (in this case) the rest of your stack past buffer. This is very dangerous behavior.

    In general, you should always create methods that supply limits. In most C libraries, these methods are denoted by an n in the method name.

    0 讨论(0)
  • 2020-12-20 01:47

    C does not do any run time bounds checking like other languages(C#,Java etc). That is why you can write things past the end of the array. However, you won't be able to access that string in some cases because you might be encroaching upon memory that doesn't belong to you giving you a segementation fault. K&R would be a good book to learn such concepts.

    0 讨论(0)
  • 2020-12-20 01:48

    As the other answers have said, you're overwriting the buffer, so for the sake of your test change it to:

    char buffer[ 12 ];
    

    For the job interview they were perhaps hoping for:

    char *mycpy( char *s, char *t )
    {
        while ( *s++ = *t++ )
        {
            ;
        }
        return s;
    }
    
    0 讨论(0)
提交回复
热议问题