Dynamic allocation, structure, union

Source: Internet
Author: User

(i) Dynamic memory allocation:

1. Why dynamic memory allocation? For example, I would like to do a student performance management system where you may need to store information about all students in each class, but

Yes, how much space do we have to allocate?? The number of each class may not be equal, according to multi-allocation, so much waste, according to less distribution, not enough. So

Dynamic memory allocation has its own role ~ ~

2. Dynamic Memory allocation function:

(1) void *malloc (unsigned int size);-------size is the number of bytes that need to be allocated.

(2) void *calloc (unsigned int num_elements,unsigned int elements_size),----num_elements is an element of the assignment

Number, Elements_size is the number of bytes each element occupies.

(3) void *realloc (void *p,unsigned int new_size),----new_size is the modified number of bytes, p is the original memory first address.

Since these functions are space in the heap, they need to be released after use-so free is coming ~ ~

(4) Void free (void *p);-----p is the first address of the space to be freed.

At first glance, malloc and calloc seem to be the same, not really. Calloc initializes this memory to 0 before returning a pointer to memory. So

We can assume that Calloc's work is equivalent to malloc plus memset. So calloc in the allocation process may be a bit slower ~ ~

The front 3 functions all need free, if no, can cause memory leaks ~ about this issue in this article click on the Open link has a detailed explanation ~

The free release needs to be set to NULL when it is finished. We have to have a principle before we use pointers----that is to judge whether it is empty before use,

You need to set NULL after. Look at the code below:

void Test () {Char *p = (char *) malloc (20*sizeof (char)), if (p = = NULL) {printf ("Out of Memory"); exit (1);} strcpy (P, "Hello");p rintf (p); free (p); if (P! = NULL) {strcpy (P, "Yaoyao");p rintf (p);} Free (p);}

What does the program actually output?? Yes, it is Helloyaoyao, memory has been released, why can copy it?? is not set as

Null. Although P has been broken with the memory of the relationship, you can have the p inside the other people's address, so ~ ~ ~

What exactly is the realloc function used for? Allocate memory, yes, can also be expanded, scaled (the scale mentioned below refers to the expansion or contraction of the volume).

Let me analyze this function in detail:

The function prototype is void *realloc (void *p,unsigned int new_size); When P is null, the function is to open up space when p is not null,

The function is to enlarge. With the code below, let me analyze it in detail:

void Test () {Char *p = (char *) malloc (char), char *preal = null;if (p = = NULL) {printf ("Out of Memory"); exit (1); }//If I find 10 space at this point is not enough, so I need to expand Preal = (char *) realloc ((void *) p,12), if (preal! = NULL) {p = preal;} Elseprintf ("Out of Memory"), free (p);}

This procedure, at first glance, seems preal this variable is not needed, in fact, it is completely necessary. When we expand, sometimes the expansion is unsuccessful (the shrinkage does not exist

In this case, REALLOC will return NULL if we assign the return value of the ReAlloc function directly to P, at which point P becomes null,

before the number It will not be found (such a row?? If the assignment succeeds, the new address is assigned to P, the assignment is unsuccessful, the error is left, and the last

Direct Release put the p on it. If you look closely, you will find that the ReAlloc parameter 1 I force type conversion, in fact, does not translate in my compiler is also available

to the. I don't know it under your compiler.

Exit () is used multiple times on the top of the program, and I'll give the Exit function a collation:

Exit () Function:

Header file: stdlib.h

Function: Closes all files and terminates the process being executed.

Exit (1) indicates an exception exit, and this 1 is returned to the operating system.

Exit (x) (x!) = 0) indicates an abnormal exit.

Exit (0) indicates normal exit.

Exit parameters are passed to the operating system.

The difference between exit and return:

By ANSI C, the effect of using return and exit is the same as in main () that was originally called.

If the main function is in a recursive program, using exit will still terminate the program, but return will transfer control to the previous level of recursion, at which point return

will terminate the program.

Another difference: Even if you call exit in a function other than the main function, it terminates the program.

The difference between _exit and exit:

_exit header file: unistd.h

Function: Direct the process to stop running, clear its memory space, and destroy its various data structures in the kernel.

Exit: The role on the basis of a number of packaging, in the implementation of the exit before doing a number of procedures.

The biggest difference: the Exie function checks the opening of a file before calling the exit system, and writes the contents of the file buffer back to the file.

3. Common memory allocation error: Dereference a null pointer (directly because there is no detection of a successful allocation), when operating on the allocated memory

Bypass the boundary, release memory that is not dynamically allocated, release part of the dynamically allocated memory, and continue to use after the memory is freed.

These errors are better understood, and there is no example here. However, I still want to give a way to prevent the first mistake to happen ~ ~

Below is a way to:

#define  malloc#define  malloc (num,type) (type *) alloc ((num) *sizeof (type)) extern void *alloc (unsigned int size )

The malloc macro receives the number of elements and the type of the element, computes the total number of bytes required, and calls Alloc for memory, Alloc calls malloc and makes

Check to make sure that the returned pointer is not NULL.

4. In fact, dynamic memory allocation is not what you think, when you apply for space, the system in fact, before this space will reserve a space to store this

The size of the memory bar. (or the number of elements to be placed)

Dynamically allocate space for an array of 3 rows and 4 columns:

Error Method 1:

int **a = (int * *) malloc (3*4*sizeof (int));
This is the way to deceive yourself. A two-dimensional array is not equivalent to a two-level pointer, as highlighted in the previous article.

Error Method 2:

void Test () {int i = 0;int *p = null;for (i = 0;i < 3;i++) {p = (int *) malloc (4*sizeof (int));} Release Ellipsis}
There is a problem with this being covered.

Here's the right way:

1.

void Test () {int i = 0;int *p[3] = {NULL};for (i = 0;i < 3;i++) {P[i] = (int *) malloc (4*sizeof (int));} for (i = 0;i < 3;i++) {free (p[i]);}}

2.
void Test () {int (*p) [4] = (int (*) [4]) malloc (4*3*sizeof (int)); free (p);}

The above code does not implement any function, just give the application space ~ ~


(ii) Structure:

1. Definition:

struct  stu{    int age;    Char name[12];} Student
The above gives a simple structure of the definition, struct Stu is a type name, analogy to int,double, such as, student is equivalent to a structural body change

Volume, remember, the type name is struct Stu, not Stu, Stu is a label, so sometimes it is more troublesome to write, we can use typedef to solve.

typedef struct stu{    int age;    Char name[12];} Stu
after that you need to define a variable of this struct type directly with Stu this type name.
typedef  struct stu{    int age;    Char name[12];    struct Stu *next;} Stu
if you want to define a struct pointer inside a struct, you cannot use "new name" because the new name does not appear .

<pre name= "code" class= "CPP" >
struct {    int age;    Char name[12];} S1,S2;


This is a non-labeled structure definition, defined two structure variables, however, you can not define the other variable ~ ~ because there is no variable name ~

Do you have a chicken or an egg first??? Chicken and egg problems in the structure:

struct b;struct a{    int age;    Char name[12];    struct  b  b;}; struct b{    int age;    Char name[12];    struct  a  A;};
B has a variable, a has a B variable, so can only sacrifice a ~ ~

2. Access: There are two ways of direct access and indirect access.

Like what:

struct stu{    int age;    Char name[12];} S,*ps;

S is a struct variable, PS is a pointer to a struct, and if you want to access an age member of a struct, we can access:

S.age

Ps->age

(*PS). Age

The first is a direct reference, the back two kinds are indirect references ~ ~

3. When the structure as a parameter needs to be passed to another function, you can pass the structure of the body, but also the address of the structure, but we generally pass the address, because

For the address only 4 bytes (32-bit system), save space, but the address of the past is more free, the function is to change, if you do not want to be repaired

Change, then you can use the Const modifier ~ ~

4. Bit segments: The declaration of a bit segment is similar to a struct, but its members are 1 or more bit segments, and these different lengths of fields are actually stored in one or more

Shaping variables. The members of a bit segment must be declared as int, unsigned int, signed int, and a colon and an integer after the member, the integer

Specifies the number of bits that the bit segment occupies.

struct a{    int a:10;    int b:2;    int c:15;};

sizeof (struct A) = 4;Although the rules say that the members of the struct can only be of the INT series, we find that the char type is also possible, but you must not marginallyruler----Mix int with char.
struct a{    char a:4;    char B:2;    char C:3;} Sa;int Main () {    sa.a =;    SA.B =;    SA.C = 9;}
Looking at the example above, let's take a look at how these variables are stored. When I knocked this code down under the VC6, the memory situation at run time
a accounted for 4 bits, so the storage is 1111,b accounted for 2 bit, so only after two bits of storage, so storage 01, because the 1th byte can not store C, so CEnter the next byte, which takes up 3 bits from the back forward. The machine is a small-end storage, so the storage is the case. Note : Portability of the program avoids using bit segments (because different platform types occupy 2 bytes of different ~~int on a platform)bit segments have different results in different systems. The int bit segment is treated as a signed number or an unsigned number. The maximum number of bits in a bit segment, for example, int in a platform 2 bytes, the maximum number is 16, on a platform is 4 bytes, the maximum number is three.Whether a member in a bit segment is left-to-right or right-to-left in memory (should be a size-side problem)not enough to put down the next member, how the machine processes ~ to save a portion of this insufficient byte, the other stored in the next 1 bytes, or directly all storagein the next 1 bytes. (iii) ConsortiumUnion unions . All of its members are in the same starting position in memory. Using this feature can be used to determine the size of the machine end ~ ~ Front of the article ishave been introduced. (iv) enumeration typetype definition: Enum Enum type name {All list of values}; (the list of values does not have a type, each is an identifier and is usually uppercase)variable definition: enum enum type name variable name;The value of the enumeration type, when there is no assignment, the default is 0, and the bottom is incremented once. Using this feature, when we do the Address Book or calculator to useSwitchstatement, each case can be written in an enumeration type, which is convenient when used. For example:
Enum  os{    WINDOWS,    LINUX,    UNIX};

These identifiers are 0,1,2 by default.

(v) Memory alignment: (The following code takes vs as an example)

When it comes to memory alignment, let's think about it: why memory alignment?? What is the use of memory alignment??

Look at this code:

struct a{    char c;    int i;};

Let's think about what is sizeof (struct A). I think most people will think that is 5, should not be I size plus C size?? Not really.

Such The result is 8. When allocating space to the structure, the memory alignment is taken into account, looking at the graph.


This is to exchange space for time. Before I say memory alignment, I have to start with these two concepts:

Default Alignment number: The default alignment number under VS is 8,linux under gcc default alignment number is 4, of course, this is not immutable ~ ~

#pragma pack (n)//The compiler will align in N-byte

#pragma pack ()//compiler will cancel custom alignment

Alignment Number: The minimum value of its own size and the default alignment number.

What are the rules for memory alignment??

(1) The first member must be aligned at 0 addresses.

(2) Each member must be aligned to the integer multiple address of the alignment number.

(3) The total size of the struct must be an integer multiple of the maximum number of alignments.

(4) The default alignment of a nested struct is an integer multiple of the largest of all the alignment numbers in the struct body.

(5) The total size of the nesting is an integer multiple of all the maximum alignment numbers.

Let's look at this example:

struct a{    char c;    Char C1;    int i;};
The size of this structure is 8, this is not difficult to determine. C's address: 0x0000,c1:0x0001,i:0x0004, so the total is 8.
struct a{    char c;    int i;    char C1;};

It is easy to make sure that the size of the structure is 12, clearly the same structure as the top, that is, the member order is different, the size is not the same

it. The order is different, in order to memory alignment, will waste some space, so, when defining the structure, consider the memory of the feeling HA ~ ~

Said so long, seems to be better to do, let's get a little bit more difficult bar ~ ~ Code ~

struct b{    char c;    Double D;}; struct a{    int A;    Char c[5];    struct b b;};

Analysis Structure a the size is how many ~32.a accounted for 4 bytes, the default alignment is 8, itself size 4 bytes, so accounted for 4 bytes of memory, the array is equivalent to 5

Char the number of types, so accounting for 5 bytes. the maximum number of alignments for struct B is 8.

So the first address of a: 0x0000,c:0x0004 (c in Structure a), c:0x0016,d:0x0024, so the total is 32. Do not give a picture, you can

Draw for yourself Oh ~ ~

The sizeof operator can derive the overall length of a struct, including those bytes wasted. If you have to determine the actual position of a member of a struct,

You should consider boundary alignment factors, and you can use the offset macro.

This macro is in the Stddet.h header file.

Offset (type,member)

Type is a struct, member is the member name you need, the result of the expression dies an unsigned shape that represents the bits that the specified member started to store

The position at which the distance structure begins to be stored is offset by several bytes. Use the nearest code to give an example:

The offset (struct b,d) result is that the 8.//b start address is 0x0016, and the start address of member D is 0x0024, so the result is 8.

About the structure, and memory allocation of knowledge first organized so much, above if there is a problem, I hope to point out ~ ~ Thank you ~

Finally inspire yourself: girls are not necessarily worse than boys ~ ~ ~

Dynamic allocation, structure, union

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.