Errors in C and C ++ languages

Source: Internet
Author: User

1. sizeof () and strlen () Functions
Sizeof common standard usage (1), (2), (3) [from C ++ Reference]:
// (1)
Char buff [6];
Strncpy (buff, argv [1], sizeof (buff ));

// (2)
Int array [] = {3, 1, 4, 1, 5, 9 };
Unsigned int array_size = sizeof (array)/sizeof (array [0]);

// (3)
Typedef struct data_type {
Int age;
Char name [20];
} Data;

Data * bob;
Bob = (data *) malloc (sizeof (data ));
If (bob! = NULL ){
Bob-> age = 22;
Strcpy (bob-> name, "Robert ");
Printf ("% s is % d years old \ n", bob-> name, bob-> age );
}
Free (bob );

 
It can be seen that sizeof is mainly used to find some data (such as int, array, String, pointer, struct ...) For example:
Char str [] = "hello ";
Char * p1 = str;
In this case, we can use sizeof (str) to get 6 characters. Because hell0 is a five character, the end ID \ 0 will be added at the end of hello, and a total of six characters will be added during storage;
Sizeof (p1) obtains 4, which is the length of the pointer variable p1. on 32-bit machines, an address is 32-bit, that is, 4 bytes.
What we get with sizeof (* p1) is 1. Because * p1 is defined as char, it is equivalent to one character, so it only occupies one byte.
Use strlen (str) to obtain 5, because the length obtained by strlen does not include the final \ 0.
Use strlen (p1) to obtain 5, which is equivalent to strlen (str.
The difference between sizeof and strlen is also the difference between the pointer string and the array string.
 
 
This type of error is very confidential during programming. See the following example.
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
Int main ()
{
Char * src = "hello world ";
Char * dest = NULL;
Int len = strlen (src); // It is prone to errors here. Writing sizeof (src) is to evaluate the length of the pointer, that is, 4
Dest = (char *) malloc (len + 1); // errors are easily indicated here, written as len
Char * d = dest;
Char * s = & src [len-1]; // errors are easily reported here, written as len
While (len --! = 0)
* D ++ = * s --;
* D = '\ 0'; // This sentence is easily missed
Printf ("% s \ n", dest );
Free (dest); // This sentence can be easily missed
Return 0;
}

 
Note: The C language program above is compiled by gcc on the Linux platform. The VC6 on the Windows platform does not support the declarative form and must be defined before use. Compiling with VC6 can be changed to the following format:
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
Int main ()
{
Char * src, * dest, * d, * s;
Int len;
Src = "hello world ";
Dest = NULL;
Len = strlen (src );
Dest = (char *) malloc (len + 1 );
D = dest;
S = & src [len-1];
While (len --! = 0)
* D ++ = * s --;
* D = '\ 0 ';
Printf ("% s \ n", dest );
Free (dest );
Return 0;
}

First, describe the use of the malloc function and the free function www.2cto.com.
# Include <stdlib. h>
Void * malloc (unsigned int size );
Its function is to allocate a continuous space of size bytes in the dynamic storage area of the memory. The function returns a pointer to the actual address of the allocated domain. The pointer type is void. If the function fails to be executed successfully, a NULL pointer is returned. This function must contain the header file stdio. h.
 
A void pointer pointing to an undefined variable, that is, it can point to a char type variable or int type or other types. Therefore, force type conversion is required when the value is assigned to another pointer. For example:
Char * p1 = "123456 ";
Void * p2 = "abcdef ";
P1 = (char *) p2; // both types must be the same, or p2 = (void *) p1;
The malloc function must be paired with the free function, and the free (dest) function is used up );
 
2. Errors in the array
 
Analyze the following small program:
# Include <stdio. h>
Void main ()
{
Int a [5] = {1, 2, 3, 4, 5 };
Int * ptr = (int *) (& a + 1 );
Printf ("% d, % d \ n", * (a + 1), * (ptr-1 ));
}
And the following program:
# Include <stdlib. h>
# Include <stdio. h>
Static void show_str_pointer (const char ** ppstr)
{
Printf ("% s \ n", * ppstr );
}
Int main ()
{
Char array [4] = "abc ";
Char * pointer = "abc ";
Show_str_pointer (& pointer );
Show_str_pointer (& array );
Return 0;
}

 
The execution result is:
Abc
7.
& The semantics of array is the same as that of array. Here, pointers and arrays cannot be exchanged. & Pointer is the pointer address. It is of the same type as the show_str_pointer parameter char ** ppstr pointer to the pointer. The & array is still the array address, which is inconsistent with the char ** ppstr type.
 
 
3. Maximum length of the array
Int n [1000000]; this certainly does not work, because the defined array uses the stack memory, the default value of the system is 1 Mb, an int occupies 4 bytes, so you can apply for a maximum of 1024*1024/4 = 264144. if you consider that the system occupies a maximum of about 25000 bytes.
Int * p = (int *) malloc (1000000 * sizeof (int); in this way, the heap memory is used, as long as you have so much continuous space in the memory. Example:
# Include <stdio. h>
# Include <malloc. h>

Int main ()
{
Int * p = (int *) malloc (1000000 * sizeof (int ));
// Int p [1000000];
Int I = 0;
For (; I <1000000; I ++)
Printf ("% d \ n", p [I] = I );
Free (p );
Return 0;
}

 
If an array is required, it is generally written in this way and cannot be larger:
# Define Max size 250000
Int a [MAXSIZE];
 
2. fscanf and fprintf Functions
Read the data in the file and store it to the specified pointer location, for example, fscanf (fp, "% d", & a [I]);
You can use the fprintf function to save data to a file, but for binary files, it is not true to write fprintf (fp, "% d", a [I, because % d is saved in decimal format, do not use fprintf. Replace it with fwrite.
Read and Write binary files in the following program:
# Include <stdio. h>
# Include <stdlib. h>
# Include <time. h>
# Define DATASIZE 250000

Int main (int argc, char ** argv)
{
Const char * file_name = "out. dat ";
FILE * fp = fopen (file_name, "wb"); // It must be placed before the definition of other variables.
Int I, a, B [DATASIZE];
Srand (time (NULL ));
For (I = 0; I <DATASIZE; I ++)
{
A = rand () % 100;
Fwrite (& a, sizeof (int), 1, fp );
}
Fclose (fp );

Fp = fopen (file_name, "rb ");
Fread (& B, sizeof (int), DATASIZE, fp );

For (I = 0; I <200; I ++)
Printf ("% d", B [I]);
Printf ("\ n ");

Return 0;
}


Program Description: randomly generate 0.25 million 0 ~ An integer of 100 is saved to the file out in binary format. dat, and then read the file out. the integers in dat are assigned to array B [DATASIZE] one by one, and the first 200 of the arrays are printed.
 
3. Recursive stack space Overflow
We know that quick sorting is usually written by recursive algorithms, although it is said to be the fastest (but not the fastest ), however, when I rank 0.2 million integers, it will not be affected. (It seems that the size of the stack space allocated by the system is 2 M or 8 M. In the worst case of fast sorting, the recursive depth is n, the required stack space is O (n), an integer of 4-bit 32 bytes, 100 W * 32, there will be more than 30 M, the stack space must overflow ), when sorting 0.18 million integers, the approximate time complexity is about 0.14 billion, and it takes 0.497 seconds to run. The qsort () in the built-in library function of VC6 is much slower, and it takes 1.942 seconds, it took only 0.032 seconds for heap sorting (awesome !), There is also the hill sorting optimized by elder brother. It took 8.518 seconds and the complexity was about 1.6 billion!
I improved the quick sorting slightly and used the first, middle, and last steps as the benchmark. The speed must have increased a lot, but the number of sortable elements has dropped to 30 thousand, 40 thousand elements may cause recursive stack space overflow, and 50 thousand elements can be ignored. Therefore, the limit of this fast sorting is 30 thousand elements. When I tested with 30 thousand elements, it took 0.169 seconds for the fast sorting and 0.006 seconds for the heap sorting.
When the amount of data to be sorted is large, you don't want to use Bubble sorting, directly select sorting, directly insert sorting, etc., the efficiency is too low! It is best to sort by heap.
 
Add:
The implementation process of recursive algorithms is implemented through stacks. For example, the following algorithm is used to calculate factorial:
Int Fac (n)
Int n;
{
If (n = 1) return 1;
Else return n * Fac (n-1 );
}
The system will not calculate it at first, and it will open up a stack space in the memory. If n = 3, then 3 * Fac (2) is first added to the stack, occupy the position at the bottom of the stack, and then 2 * Fac (1) into the stack, Fac (1) is no longer recursive, so there is no element re-stack, Fac (1) returns 1, then 2 * Fac (1) and 3 * Fac (2) go out of the stack in sequence, and the number 6 is the number 6, which is the factorial of 3.
It can be seen that the more complex recursive functions are, the larger the data volume and the more variables there are, the larger the space occupied by the stack. Because each layer of the stack needs to be saved, there are actually many duplicates, but it is still saved and released only when the stack is released. The compiler is like this. There are not many optimizations, and the memory overhead is quite large. So -- use less recursion and use recursion with caution!

From jicao...
 

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.