You have to know the pointer base -4.sizeof to calculate the length of the array and the security issues of strcpy

Source: Internet
Author: User

First, using sizeof to calculate the array length 1.1 sizeof basic use

If the variable is declared as an array within the scope, you can use sizeof to find the array size, and the following code shows how to use sizeof:

    intNums[] = { One, A, -, -, -, the}; inti; //sizeof (Nums) calculates the total number of bytes in the nums array//sizeof (int) calculates the number of bytes occupied by the int type    intLength =sizeof(nums)/sizeof(int);  for(i=0; i<length;i++) {printf ("%d", Nums[i]); }

where sizeof (Nums) represents the total number of bytes of the nums array, and sizeof (int) represents the number of bytes that are used to calculate the int type (32-bit system is 4 bytes, the 64-bit may be different, so sizeof (int) This difference can be masked to the programmer) and the result is:

1.2 sizeof can only be evaluated at compile time

If we make an abstraction of the above code, we encapsulate the traversal and printing of the array as a method, the code is as follows:

voidPrinteach (int*nums) {    //sizeof (Nums) is here to calculate the number of bytes of a pointer    intLength =sizeof(nums)/sizeof(int); printf ("The length of Nums is%d\n", length); inti;  for(i=0; i<length;i++) {printf ("%d", Nums[i]); }}

We define a Printeach method whose parameters are a pointer to the array length within the method by sizeof. However, the results of the operation are not consistent with the results above:

We found that although we used pointers, it was not possible to calculate dynamically because sizeof was calculated by the compiler at compile time . So for int * or to pass an array to a function, it is not possible to use sizeof to get the size. Not even if int[is written in the function declaration (to avoid misunderstanding, do not declare the array type in the argument). Here, sizeof (nums) just calculates the number of bytes of the pointer (where the pointer points to the address of the first element of the array, an int takes 4 bytes, so the last length becomes 1).

So, in order to avoid the inability to calculate the length of the case, we usually add a length parameter to the method definition, let the caller pass it over, the function is no longer calculate the length of the inside. Look at the following code:

void printeachwithlen (int* nums,int  length) {    int  i;      for (i=0; i<length;i++)    {        printf ("", Nums[i]);}    }

At this point, we can call the Printeachwithlen () function in the main function:

int sizeof (nums)/sizeof(int);p Rinteachwithlen (nums,length);

Here's a look at the results:

Therefore, it is generally necessary to pass the "Length" argument to the function when passing an array/string, because inside the function there is no known "how Long". For example: memcpy (void * restrict, const void * restrict, size_t), and the third parameter size_t is the length. And, for example, in. NET, in order to copy the array, you can use array.copy, buffer.blockcopy,array.constrainedcopy, and so on, by looking at its method definition, it is required to pass the array length.

Const intInt_size =4;int[] arr = {2,4,6,8,Ten, A, -, -, -, - }; Buffer.blockcopy (arr,3* Int_size, arr,0* Int_size,4*int_size);foreach(intValueincharr) Console.Write ("{0}", value);//The example displays the following output://8 in ten
Ii. strcpy Security Issues 2.1 using strcpy to copy strings

A simple scenario in which a string is copied into another string, and in the C language textbook, the longest occurrence is strcpy. We can easily write the following code to implement string copying:

Char " Hello Edison " ; Char deststr[];strcpy (deststr,sourcestr);p rintf ("%s", DESTSTR);

The results of the operation are as follows:

However, we often hear people say that strcpy is not a safe function, why? First look at the strcpy inside the loop to determine the condition:

 while '  / ')

This loop is executed until the loop condition is empty, that is, ' strdest ', that is, if the storage space referred to by the STRSRC is not large enough, the function copies some of the contents of the strdest into memory behind the memory space referred to by the reference . The memory behind Strdest's space is unknowable and may have been consumed by other resources, destroying what was originally stored and causing the system to crash.

Because strcpy executes a string copy, it detects whether the data stored in the current memory cell is ' \ ", starting at the point where it is strsrc. if it is not, the data in this memory unit is copied to the memory pointed to by Strdest . If the length of the string stored in the STRSRC is greater than the memory space requested by DST, it can result in unpredictable consequences.

PS:strlen The end of the string according to ' "", then a malicious attacker can construct a string that does not contain ' a ', and then let the data write to the program memory space outside the array, thereby destroying it.

2.2 Using strncpy instead of strcpy

(1) strncpy function definition:

Char *strncpy (charconstchar *src,int count)

Copies the count characters from the string src to the string dest, and finally returns a pointer to Dest.

(2) strncpy usage Analysis:

This function is similar to strcpy, when the length of SRC is greater than the space of the DST application, the situation is the same as strcpy;

If the value of the 3rd parameter count is greater than the length of the string in src, the string src is copied to DST, returning the function.

Note: If the source string length is greater than N, then strncpy does not copy the last '% ' terminator, so it is not secure and requires a terminator to manually add strings after the copy is finished.

(3) strncpy Usage Example:
CharSourcestr[] ="Hello Edison";Chardeststr[ -];intLen =sizeof(SOURCESTR)/sizeof(Char);p rintf ("%d\n", Len); strncpy (Deststr,sourcestr,len-1);//Guaranteed Secure String Replicationdeststr[len-1]=' /';p rintf ("%s", DESTSTR);

The results of the operation are as follows:

Resources

such as Peng Network, "C language can also do big Things (third edition)"

Zhou Xurong

Source: http://edisonchou.cnblogs.com

The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.

You have to know the pointer base -4.sizeof to calculate the length of the array and the security issues of strcpy

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.