Pointers and Memory __ pointers

Source: Internet
Author: User
Tags memory usage shallow copy
Pointers and Memory

2017-04-26 Why do you use pointers

Pointers solve two types of software problems. First, pointers allow different parts of the code to simply share information. Copying information before and after can achieve the same effect, but pointers can better solve the problem. Second, pointers support complex relational data structures such as lists and two-fork trees. What's the pointer?

The pointer stores one worthwhile reference rather than the value itself. Pointer dereference

The dereference operation is after a pointer reference to obtain the value of the pointer data. It is simple to get the value of the pointer data when the dereference operation is used correctly. The only limitation is that the pointer must have pointer data to dereference it. Almost all bugs in the pointer encoding involve breaking this qualification. The pointer must allocate pointer data before the dereference takes effect. (That is, the pointer must have something to point to) null pointer

Constant NULL is a special pointer, which means nothing. NULL provides a convenience for setting pointers with no pointer data. The dereference null pointer belongs to a run-time error. null and integral constant 0 are equivalent, so they can be used as logic. Formal C + + no longer uses null symbolic constants--use integer constants directly. Symbol NULL is used in Java. pointer Assignment (Assignment)

Assigning values to each other between two pointers causes them to point to the same pointer data. For some potentially complex situations, it can be very convenient to assign values to each other, and the reciprocal assignment of pointers does not change the value of the pointer data, only the pointer data that the pointer points to. Assignment operations are also valid for null values. Assignment with a null pointer passes the null value from one pointer to the other. Paint

The memory diagram is the key to considering the pointer code. When you look at the code, think about how it uses memory at runtime, and quickly draw a chart to your mind. shared

Two pointers to the same pointer data are called "shares." In any computer language, two or more entities sharing the same storage structure are the primary advantages of pointers. Pointer manipulation is just a trick, and sharing is the real goal. Sharing can be used to provide efficient communication in different parts of the program. , shallow copies, and deep copies

In particular, a share can support communication between two functions. A function passes a pointer to an interest value to another function. Both can obtain the interest value, but the interest value itself is not copied. This type of communication is called a "shallow copy" because it is a (small) pointer that is passed a (large) copy of the interest value sharing rather than the value of the interest. The receiver needs to understand that they have a shallow copy, so they know not to change or delete the data because it is shared. The optional values that are fully copied and sent are called "deep copies." In a way, deep copy is simpler, but because it is full copy, the deep copy runs slightly slower. Bad Pointers

When a pointer is assigned for the first time, it does not correspond to (point to) pointer data. The pointer is "uninitialized" or, in short, bad. The dereference of a bad pointer is a very serious run-time error. If you're lucky, the dereference will crash immediately (Java will run). If you are unfortunate, the dereference of a bad pointer invades a random area in memory, slightly changing the program's operation, and eventually causing a crash in the next indeterminate time period. All pointers must point to pointer data before the dereference operation is supported. Before pointing to pointer data, the pointer is a bad pointer and is not allowed.

Bad pointers are very common, in fact, each pointer starts with a bad value. The correct code uses the correct reference to the pointer data to duplicate the bad value, and the pointer works correctly thereafter. The pointer does not automatically give the legal value.

Draw the key

Many languages need to be careful to omit this critical step for simplicity. If the code collapses, the bad pointer is the first one to suspect.

Pointers are somewhat different in dynamic languages such as Perl,lisp,java. When the pointer is assigned, the system points the pointer to null, and each dereference is checked for legality. So the code can still display pointer bugs, but they will gracefully stop in the warning area instead of crashing like C. Also, in dynamic languages, it is easier to locate and fix pointer bugs. Runtime checking is also why such languages are always slower than compiled languages such as C or C + +. two levels

Both the pointer level and the pointer data level require initialization and connection to work at two levels. Assigning pointer assignment pointer data pointer to pointer data type syntax

int* type: pointer to int
float* type: pointer to float
struct fraction* type: pointer to struct fraction
struct fraction** type: pointer to struct fraction * pointer variable

Variables are declared to the new variable type and storage space to store the value. The declaration does not point the pointer at the pointer data, that is, the bad pointer is declared. & operator (take address operator)

There are many ways to get references to pointer data, the simplest of which is the & address operator.

Using & it is possible to compile through but error at run time. * operator (dereference)

The pointer must correspond to the pointer data, or it is a run-time error.

Assignment pointers do not automatically assign values, and you need to manually assign a reference to a specific value to the pointer, which is a standalone operation that you often forget. How the pointer executes in the machine

In short, every area in memory has a numeric address like 1000 or 20452. The pointer is the address. The dereference operation is to look at the address stored in the pointer and then extract the pointer data to the appropriate address. A null value is usually a numeric address 0. The computer never assigns a value to a 0 address, so the address can be used to represent null. A bad pointer is actually a pointer that contains a random address--just as an int variable that has not been initialized starts with a random int variable. The pointer has not yet been assigned a reference to the specific pointer data. This is why the dereference operation with bad pointers is so unpredictable. entry "Reference"

The reference and pointer meanings are similar, except that references are often used as a discussion pointer problem, not for a language or implementation. "Pointer" implies that C + + is implemented as a pointer to an address. why bad pointers are so common

Mind-set. Simple variables do not require additional settings, they can be used directly after the declaration, such as int,char,struct fraction and so on. Unfortunately, pointers are not simple variables and require additional initialization before they are used. Part II-local storage allocation and release of memory

Variables represent the storage space of your computer's memory. Not every variable in the program has a fixed allocation of memory. In terms of the term, when a variable has a piece of memory that holds its value, it is called an assignment. When a system reclaims memory space from a variable, it is called release, and it no longer has space to store the value. For a variable, this period of time from allocation to Shifang is called the life cycle of the variable.

The most common error usage of memory is to use a freed variable. For local variables, modern languages automatically prevent this error. For pointers, the programmer must verify that the allocation is handled correctly. Local Storage

Local variables are the most common variable.

Variables are called "local", meaning that their lifecycle and functions are tied together. Born with a function, dead and dead.

The only difference between a parameter and a local variable is that the parameter is passed from the caller and the local variable starts at the random initialization value. the advantages of local variables are convenient-local variables to meet the fast use, functions usually require temporary memory, only need to be in the scope of the function calculation valid. Local variables provide this type of temporary, isolated memory easily. Effective-local variables are very effective compared to other memory usage techniques. High-efficiency (fast) allocation and release, high space efficient, recyclable. Local replication--local parameters are basically copied from the caller, which is also commonly referred to as "value delivery." A parameter is a local variable that comes from a copy of the caller's assignment. Instead of "sharing" parameter values like pointers, the caller gets its own copy. Disadvantages of local variables

Short life cycle-can be solved by heap;

Restrictive communication--because local variables are copies of call parameters, they do not provide communication from the callee to the caller, which is synonymous with the negative impact of the "independence" advantage "local"

Local variables are also referred to as "automatic" variables because they are allocated and released as part of a function mechanism. Local variables are sometimes called "stack" variables because, from the bottom up, languages typically implement local variables through memory stacks.

tab--the ampersand Bug function
//Returns a pointer to a int
int* tab () {
int temp;
return (&TEMP); Return a pointer to the local int
}
void Victim () {
int* ptr;
ptr = TAB ();
*ptr = 42; Runtime error! The pointee is local to TAB
}
Summary of local variables the problem to be solved

How a function feeds data back to its caller.

How a function allocates an independent space function with fewer life cycle limits How call stacks work reference parameters

In the simplest "value pass" or "parameter" methods, each function has a separate local memory, and when the function is invoked, the parameter is copied from the caller to the callee. But how to communicate from the callee to the caller. Using the "return" copy result at the bottom of the called function to pass it back to the caller, this method works for some simple situations, but not in some complex cases. Sometimes it is not feasible to copy values back and forth. The reference pass parameter solves all the problems.

"Interest value" refers to the value that the caller and the callee want to pass between them. A pointer to a reference parameter passing an interest value rather than a copy of the interest value. This approach leverages the sharing of pointers, so callers and callers can share interest values. Grammar

In C, the syntax for referencing a parameter is to manipulate the pointer

A person with one watch always knows what time it is. A person with two watches is never sure.

Avoid copying. about &bug

Using & passing pointer variables from the caller to the callee to the local store is fine, in turn, from the callee to the caller, there will be &bug, because once the function exits, the memory is released and the pointer is invalidated. the situation of * *

If the value of interest is already a pointer, such as int* or struct fraction*. Does this change the rules for setting reference parameters? Not going to. The reference parameter is still a pointer to the value of the interest, and several times the interest value itself is the pointer. Suppose the interest value is int. This means that the interest value itself is an int value, which is shared by the caller and the callee. So the reference parameter should be int**. The value of interest can be obtained for a single dereference operation of a reference parameter as before. Two (*) pointer parameters are common in the list. Heap Memory

Heap memory, also known as dynamic memory, is an alternative to local stack memory. Local memory is too automated, heap memory is different, the programmer for "block" memory request a specific size of memory allocation, this block will always exist until the programmer explicitly request to free space. Nothing is going to be done automatically. So the programmer heap memory has greater dominance, but also has a greater responsibility because memory must now be actively managed. The advantage of heap memory is that:

Lifecycle-since programmers can now control the allocation and release of memory, build data structures in memory and return data structures to the caller. This is not possible in local memory because the memory is automatically freed when the function exits.

Size-the size of the allocated memory can be controlled in more detail. For example, string buffering can be allocated at run time, and can happen to accommodate the size of a string. In local memory, the code prefers to buffer as large as possible to ensure the best results. The disadvantage of heap memory is that:

The workload becomes larger--heap allocation needs to be detailed in the code, the workload becomes larger;

Bugs are getting more--because memory allocations now need to be done manually, possible misoperation can lead to memory bugs. Local memory is binding, but at least there will never be an error.

However, many problems can only be solved with heap memory. In programming languages with garbage collector, such as Perl,lisp, or Java, the disadvantages are largely ignored. The garbage collector takes over many of the heap management responsibilities and spends some extra time processing at runtime. What's a heap like?

A heap is a large chunk of memory that can be used by a program in memory. Programs can be in the application memory area or memory block. In order to allocate a block of memory of a certain size, the program makes an explicit request by calling the heap allocation function. The allocation function reserves the memory block of the requested size in the heap and returns a pointer to the memory block. Suppose a program makes three memory allocation requests in the heap to store three separate GIF images, and after each figure 1024 byte three requests, memory may be like this:

Each allocation request allocates contiguous areas in the heap for the requested size, returning a pointer to the range for the program, and the block often acts as the pointer data, and the program always operates through the pointer heap heap. Heap block pointers are sometimes referred to as "base address" pointers, because they point to the base of the block (the smallest address byte), as per the rules

In the example above, the three blocks of memory are continuously allocated from the bottom of the heap, each of which is at the requested size of 1024 bytes. In fact, heap management can be allocated anywhere in the heap, as long as the blocks do not overlap, or at least the continuous size of the request. In special cases, some heap areas have been assigned to programs, so they are "in use." Heap management satisfies each free memory pool from the allocation requirement, updating private data structures with which areas in the first-level library are in use. Release

When a program finishes using a block of memory, it needs to make a clear release request for heap management: The program has ended the use of the block. The heap management updates its private data structure to show that the area occupied is ready for reuse.

After the release, the pointer continues to point to a block that has been freed. The program cannot get the pointer data at that point. The pointer is still there, but it can't be used. Sometimes the code sets the pointer to null, and once the memory is released, it is explicitly illegal. Programming Heap

In most programming languages, the programming heap looks very similar, and the basic features are:

A heap is an area of memory in which the program allocates memory regions or memory blocks;

Some of the heap management Library code is the program management heap. The programmer makes a request to heap management, which in turn manages the internals of the heap. In C, the heap is managed by the malloc (), free () and realloc () functions in the ANSI library.

Heap management uses its own private data structures to track which blocks in the heap can be used, which blocks are being used, and how large these blocks are. Initially, all of the heaps are available.

The heap may be a fixed size (usually conceived), or it appears to be a fixed size, and in fact there is a virtual inner support behind it. In either case, the heap may become full if its memory is allocated, it cannot respond to the new allocation request at this time. The allocation function in some way passes the runtime environment to the program at this time-typically by returning a null pointer or by throwing a specific run-time exception.

The allocation function requests a block of a specific size in the heap. Heap Management Select a piece of memory to satisfy the request, mark the area in its own data structure as it is in use, and return a pointer to the heap block. This block ensures that the call function is reserved for use alone-the heap does not assign the same memory area to other calling functions. The block does not move around the heap-once assigned, the address and the urine are fixed. Usually, a block is assigned, its contents are random, and the new owner has the responsibility to make this piece of meaning. Sometimes, there is a variable on the memory allocation function that sets the block to 0;

The release function is the opposite side of the assignment function. The program makes a single release call to return a piece of memory to the heap free area for reuse. Each block should be released only once. The pointer to the release function is consistent with the allocation function, that is, the pointer returned by the assignment function, not any pointer to the zone. After release, the program must treat the pointer as a bad pointer and not allow the pointer data to be obtained. C Implementation

In C, the library functions for the application heap are malloc () and free (). The prototypes of these functions are in < Stdlib.h >. Although different language grammars differ, malloc () and free () are basically the same in all languages.

The C operator sizeof () is a convenient way to compute the size in bytes of a type-sizeof (int) for an int pointee,sizeof ( struct fraction) for a struct fraction pointee.

The pointer passed to free () must happen to be a pointer that was previously allocated by malloc rather than somewhere in the block. Calling free with the wrong pointer is a common crash error. Calls to free () do not need to provide the size of the heap block--the heap management is recorded in its private data structure. If the program releases all allocated memory correctly, a free () call is immediately after each malloc () call. The real problem is that for a program to release each allocated block is not always necessary, see "Memory Leak" below. Heap String Observation results

Stringcopy () contains two important advantages of heap memory:

Size--stringcopy can specify the size of the block used to store strings at run time, when the malloc () function is invoked. Local memory cannot do this because its size has been specified at compile time.

The call to sizeof (char) isn't really necessary, since the size of char is 1 by definition.

The lifecycle--stringcopy () allocates blocks, but then passes ownership to the caller. If you do not call free (), the block will always exist and the timer function exits. The local variable cannot be done. The caller needs to carefully watch the release of the memory when the string is finished. Memory Leaks

What happens if the memory is heap-allocated but not freed. A program that is allocated and forgets to release memory may or may not have serious problems. The result will be: always applying until there is no available memory space. For a running, calculated program that exits immediately after, memory leaks are usually not a concern. This "one-off" program, in most cases, ignores all releases and still works well. A memory leak usually occurs on a program with an indeterminate end time. In this case, the memory leak will slowly fill the heap until the allocation request is not met, the program stops working, or crashes directly. Many commercial programs have problems with memory leaks, so when they run for a long time, or if there is a large dataset, the heap collapses. Often, error detection and prevention codes for the full heap are not well tested, many of which are rarely encountered in running a program-that is, why a full heap usually leads to a direct crash rather than a friendly error message. Many compilers have the "heap debugging" feature, which adds debug code to track each allocation and release. When the allocation is not released, is a leak, heap debugging will help you find them. Ownership

Stringcopy () Allocates the heap block, but it is not freed. This is why the caller can use the new string. However, this also means that the release operation requires a programmer to complete, stringcopy () regardless. It is also explained in detail in stringcopy () that the caller owns the ownership of the block. Each block of memory has an exact owner responsible for releasing it. Other entities can have pointers, but they are just shares. Only a unique owner. A good document always remembers discussing the ownership rule of a function that expects it to be applied to its parameters or values. Or so, the frequent error in the document is forgetting to mention what the rule of attribution of a parameter or return value is. This is a cause of memory errors and leaks. Ownership Model

The two common patterns of ownership are:

Caller ownership-The caller has its own memory. For shared purposes, it may pass a pointer to the callee, but the caller holds the ownership. When the callee is running, the callee can get something, allocate its own memory, but should not destroy the caller's memory.

The callee assigns and returns--the callee allocates some memory and then returns it to the caller. This usually occurs when the callee evaluates the result and requires new memory storage and expression. The new memory is passed to the caller, so they can see the result, and the caller must take over the ownership of the memory. This is the pattern of the stringcopy () function description. Heap Memory Summary

Heap memory provides programmers with greater control--chunks of memory can request any size, leaving allocations until explicitly released. Heap memory can be passed back to the caller because the function exited without automatic release, which can be used to build chain structures such as linked lists and two-fork trees. The disadvantage of heap memory is that the program must explicitly allocate and release the heap memory. Heap memory is not processed automatically as local memory.

/* Given a C string, return a heap allocated copy of the string. Allocate a block in the heap of the appropriate size, copies the "string into the" block, and returns a pointer to the bloc
K. The caller takes over ownership of the "block" and is responsible for freeing it. * * char* stringcopy (const char* string) {char* newstring; int len; len = strlen (string) + 1;//+1 to account for the "" ' newstring = malloc (sizeof (char) *len); Elem-size * number-of-elements assert (newstring!= NULL); Simplistic error check (a good habit) strcpy (newstring, String); Copy the passed in string to the "Block Return" (newstring); Return a ptr to the ' block} ' 

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.