Linux application FAQ: strcpy () function in C

Source: Internet
Author: User
Common Questions for Linux applicants: strcpy () function in C-general Linux technology-Linux programming and kernel information. For details, refer to the following. Many companies use this function to test some skills of candidates, such as code style and code maturity.

First, we should avoid misleading Code such as while (* dest ++ = * src ++) in some Chinese textbooks.

I wrote the reference as follows (pure C code ):

-----------------------------------------------------------------------------

000

001 # include

002

003 # define BOUNDS_VIOLATED (_ builtin_trap (), 0)

004

005 # define CHECK_BOUNDS_LOW (ARG )\

006 (_ ptrvalue (ARG) <_ ptrlow (ARG) & BOUNDS_VIOLATED ),\

007 _ ptrvalue (ARG ))

008

009 # define CHECK_BOUNDS_HIGH (ARG )\

010 (_ ptrvalue (ARG)> _ ptrhigh (ARG) & BOUNDS_VIOLATED ),\

011 _ ptrvalue (ARG ))

012

013/* copy src to dest */

014 char *

015 strcpy (char * dest, const char * src)

016 {

017 register char c;

018 char * _ unbounded s = (char * _ unbounded) CHECK_BOUNDS_LOW (src );

019 const ptrdiff_t off = CHECK_BOUNDS_LOW (dest)-s-1;

020 size_t n;

021 do {

022 c = * s ++;

023 s [off] = c;

024} while (c! = '\ 0 ');

025 n = s-src;

026 (void) CHECK_BOUNDS_HIGH (src + n );

027 (void) CHECK_BOUNDS_HIGH (dest + n );

028 return dest;

029}

030

Note the following:

1. The 003rd rows macro call function is a pointer out-of-bounds Trap System Call (bounds check, that is, int $5 );

2. usage of the '&' and 'in the 006th rows in the macro;

3. Define data types, such as ptrdiff_t and size_t;

4. Why is the 023rd s pointer efficient? For example, the number of registers is the minimum;

5. 026th what is the returned void type;

If you are familiar with this, I believe no company can immediately reject you.

If you have any questions, study and grow together.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.