C programming errors related to size_t-memset and memcpy Functions

Source: Internet
Author: User

Abstract: when programming C language, you often need to use functions such as memset to initialize arrays or struct. This is a double-edged sword and can easily lead to unexpected bugs. This article mainly analyzes the usage traps of memset functions.


1. a preliminary study of sizeof

The following code is available:

Int a [100], int * B =;

Try to answer these questions: Is sizeof a function? What is the return value of sizeof? Is 100 or 400? What about sizeof B?

Test it by yourself and find the answer.

Conclusion: sizeof is not a function. The returned value is sizef_t, which indicates the size of the byte occupied by the element. Note that it is an unsigned type.


2. Pay attention to function interfaces.

The following code is available:

Int a [100]; memset (a, 0,100 );

Will each element of array a be initialized to 0?


3. Implementation of the memcpy Function

There was a classic problem during the interview: programming and implementing the memcpy function. Its function prototype is as follows:

Void * memcpy (void * dest, const void * src, size_t n );

How to implement it?

Pay attention to the memory overlap and NULL pointer problems, and the negative number of incoming n.

This article does not provide an answer. You can write the answer yourself and compare it with the functions in the standard library.


Related Article

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.