寫一個函數,完成記憶體之間的拷貝

來源:互聯網
上載者:User

memcpy source code:
    270 void* memcpy( void *dst, const void *src, unsigned int len )
    271 {
    272    register char *d;
    273    register char *s;
    27
    275    if (len == 0)
    276      return dst;
    277
    278    if (is_overlap(dst, src, len, len))
    279      complain3("memcpy", dst, src, len);
    280
    281    if ( dst > src ) {
    282      d = (char *)dst + len - 1;
    283      s = (char *)src + len - 1;
    284      while ( len >= 4 ) {
    285          *d-- = *s--;
    286          *d-- = *s--;
    287          *d-- = *s--;
    288          *d-- = *s--;
    289          len -= 4;
    290      }
    291      while ( len-- ) {
    292          *d-- = *s--;
    293      }
    294    } else if ( dst < src ) {
    295      d = (char *)dst;
    296      s = (char *)src;
    297      while ( len >= 4 ) {
    298          *d++ = *s++;
    299          *d++ = *s++;
    300          *d++ = *s++;
    301          *d++ = *s++;
    302          len -= 4;
    303      }
    304      while ( len-- ) {
    305          *d++ = *s++;
    306      }
    307    }
    308    return dst;
    309 }

附帶對程式的解釋是:

公司考試這種題目主要考你編寫的代碼是否考慮到各種情況,是否安全(不會溢出)
各種情況包括:
1、參數是指標,檢查指標是否有效
2、檢查複製的源目標和目的地是否為同一個,若為同一個,則直接跳出
3、讀寫權限檢查
4、安全檢查,是否會溢出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.