C Language Memory leak sample __c language

Source: Internet
Author: User
The importance of proper memory management

C and C + + programs that have memory errors can cause various problems. If they leak memory, the running speed slows down and eventually stops running, and if memory is overwritten, it becomes very vulnerable and vulnerable to malicious users. From the 1988 famous Morris worm attack to the latest security alerts about Flash Player and other key retail-level programs, the buffer overflow has been associated with: "Most computer security vulnerabilities are buffer overflows," Rodney Bates wrote in 2004.

Many other common languages (such as Java™, Ruby, Haskell, C #, Perl, Smalltalk, and so on) are widely supported in places where C or C + + is available, and each language has many enthusiasts and advantages. However, from a computational point of view, the main advantages of each programming language over C or C + + are closely related to ease of memory management. Memory-related programming is so important that it is so difficult to apply correctly in practice that it dominates all other variables or theories of object-oriented programming languages, functional programming languages, advanced programming languages, declarative programming languages, and other programming languages.

As with a few other types of common errors, memory errors are a hidden hazard: they are difficult to reproduce, and symptoms are often not found in the corresponding source code. For example, whenever and wherever a memory leak occurs, it can be as if the application is completely unacceptable and memory leaks are not obvious.

Therefore, for all of these reasons, special attention needs to be paid to memory issues in C and C + + programming. Let's take a look at how to solve these problems before we talk about which language.

Category of Memory errors

First of all, don't lose heart. There are many ways to deal with memory problems. Let's first list all possible practical problems: Memory leak error allocation, including a large increase in free () freed memory and uninitialized reference dangling pointer array boundary Violations this is all types. These types do not change significantly, even if they are migrated to C + + object-oriented languages, and the memory management and reference models in C and C + + are all the same, regardless of whether the data is a simple type or a C-language struct or C + + class. The vast majority of the following are "pure C" language, for extended to C + + mainly for practice use.

Memory Leaks

A memory leak occurs when a resource is allocated, but it is never reclaimed. Here is a model that may be wrong (see Listing 1):
Listing 1. Simple potential heap memory loss and buffer coverage

void F1 (char *explanation) {char *p1; p1 = malloc (MB); sprintf (P1, "The F1 error occurred because of '%s '.", explanation) ; Local_log (p1); }

Did you see the problem? Unless Local_log () has unusual responsiveness to free () freeing memory, each call to F1 will leak 100 bytes. A single leak is trivial when the memory stick increments the number of megabytes of memory, but after a few hours of continuous operation, even such a small leak can weaken the application.

In actual C and C + + programming, this is not enough to affect your use of malloc () or new, and the sentence at the beginning of this section mentions that "resource" is not just "memory", because there are examples similar to the following (see Listing 2). FILE handles may differ from memory blocks, but they must be given equal attention:
Listing 2. Potential heap memory loss from resource error management

int Getkey (char *filename) {FILE *fp; int key; fp = fopen (filename, "R"); FSCANF (FP, "%d", &key); return key;}

The semantics of fopen require complementary fclose. In the absence of fclose (), the C standard cannot specify what happens, most likely a memory leak. Other resources, such as semaphores, network handles, database connections, and so on, are also worth considering.

Memory Error Allocation

Incorrectly assigned management is not very difficult. The following is an example of an error assignment (see listing 3):
Listing 3. Uninitialized pointers

void F2 (int datum) {int *p2;/* uh-oh! No one has initialized P2. * * *p2 = datum; ... }

The good news about such errors is that they generally have significant results. Under aix®, assigning an uninitialized pointer usually causes an segmentation fault error immediately. The advantage of this is that any such error is detected quickly, and the cost of detecting such errors is much less than a mistake that takes months to determine and is difficult to reproduce.

There are multiple variants in this type of error. Free () frees more memory than malloc () (see Listing 4):
Listing 4. Two incorrect memory release

/* Allocate once, free twice. */void F3 () {char *p, *pp p = malloc (10);
Pp=p;
Free (p); ... free (PP); }/* Allocate zero times, free once. */void F4 () {char *p;
...
/* Note This p remains uninitialized here. * FREE (p); }

These errors are usually not too serious. Although the C standard does not define specific behavior in these situations, typical implementations ignore errors or tag them quickly and unambiguously; In short, these are security situations.

dangling Pointer

Dangling pointers are tricky. A dangling pointer occurs when a programmer uses resources after the release of memory resources (see listing 5):
Listing 5. Dangling pointers

void F8 () {struct x *xp; xp = (struct X *) malloc (sizeof (struct x)); xp.q = = ... free (XP);/* problem! There ' s no guarantee that the memory blocks to which XP points hasn ' t been overwritten. * * return XP.Q; }

Traditional "debugging" is difficult to isolate dangling pointers. They are difficult to reproduce for two obvious reasons: even if the code that affects the early release of memory is localized, the use of memory may still depend on the application or even (in extreme cases) other execution locations in different processes. Dangling pointers can occur in code that uses memory in subtle ways. As a result, it is difficult to recognize that the new value is an error value even if there is a release immediately after it is overwritten and the new point value is different from the expected value. Dangling pointers are constantly threatening the running state of a C or C + + program.

array Bounds violation

Array boundary violations are dangerous and are the last major category of memory error management. Look back at Listing 1 and what happens if the length of the explanation exceeds 80. Answer: Unpredictable, but it may be far from good situation. In particular, C copies a string that is not suitable for 100 characters assigned to it. In any general implementation, the "over" character overwrites other data in memory. The layout of data allocations in memory is complex and difficult to reproduce, so no symptoms can be traced back to a specific error in the source code level. These errors usually result in a loss of millions of of dollars.

/

. Tricky memory leaks
static char *important_pointer = NULL; void F9 () {if (!important_pointer) Important_pointer = malloc (important_size);. if (condition)/* ooops! We just lost the reference Important_pointer already held. * * Important_pointer = malloc (different_size); ... }
Do does not return a pointer to a local pointer variable or a local variable unless it is a static local variable
Char *f0 () {char temp[]= "123456789";//plus static is correct
return temp; }
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.