About C-language memory allocations, Malloc,free, and segment errors, memory leaks

Source: Internet
Author: User

1. C-language functions malloc and free

(1) function malloc and free in header file <stdlib.h> prototype and parameters

void * malloc (size_t size)

Dynamic configuration memory, size is determined, the return value succeeds with any type of pointer, and fails with null.

void free (void *ptr)

Releases the memory space of the dynamic request, calls free (), and the memory space that PTR points to is retracted, and an unpredictable error occurs if PTR points to an unknown place or the space pointed to is retracted, and if PTR is null,free, it will not have any effect.

(2) Typical usage in C language

T is any data type

T *p = (T *) malloc (sizeof (t) * N)

if (null= =p)

{

printf ("malloc fail!\n");

...//handling of related resource recoveries

Exit (-1);

}

...//This process cannot change the direction of the pointer p, if the pointer is changed, then free will be wrong, because the free is not the original P pointer, but the change. Of course, if you change the direction of P, then you have to point P back to the original position before free. That's fine.

Free (p);

P=null;

Note: The return value is usually judged after malloc to avoid unnecessary errors.

Note that it's best to get rid of P again, plus p=null.

the "wild Pointer" is not a null pointer, it is a pointer to "junk" memory (memory not available) . It is generally not wrong to use a null pointer because it is easy to judge with an if statement. But the "wild pointer" is dangerous, if it is not possible to determine whether a pointer is a normal pointer or a "wild pointer". Having a good programming habit is the only way to avoid "wild pointers". The pointer P is not set to null after the free or delete, which makes the person think P is a valid pointer. Don't look at the names of free and delete (especially delete), they just release the memory that the pointer refers to, but do not kill the pointer itself. At this point the pointer is "junk" memory. The released pointer should immediately set the pointer to NULL to prevent the "wild pointer" from being produced.

(3) Memory description

The memory space that the MALLOC function dynamically requests is in the heap (and the general local variable is stored in the stack), and the memory is not initialized , not the same as the global variable, if it is not freed with manual free (), the memory is always present. The system should not be used until the program exits, so in order to use memory properly, you should call free () when the memory is not applicable. In addition, if malloc is used in a function, it is best to pair it with free, otherwise it is likely to cause a memory leak (no memory is returned to the storage area).

However, there is often a segment error when free.

The correct approach is this:

Add a sentence before allocation to determine if the pointer is empty to prevent a memory leak

struct XXXX * ptr=null;
if (ptr = = NULL) {
ptr = (struct xxxx *) malloc (num * sizeof (struct XXXX);

}

Add a sentence before releasing to determine if the pointer is empty to prevent an exception from being generated
if (ptr! = NULL) {
Free (PTR);
ptr = NULL;

}

Add: The C language as a standard programming language on Linux systems gives us great control over dynamic memory allocation.


However, this freedom can lead to serious memory management problems, These problems can cause the program to crash or cause performance degradation over time.

memory leaks (that is, a corresponding free () call within malloc () will never be released after execution) and buffer overflows, such as writes to memory previously allocated to an array, are common problems that may be difficult to detect. This section discusses several debugging tools that greatly simplify the process of detecting and locating memory problems.

Once you have added a header file in your code and defined Memwatch in the GCC statement, you can track memory leaks and errors in your program. The Memwatch supports ANSI C, which provides results logging, detection of double release (Double-free), error release (erroneous free), memory not freed (Unfreed memories), overflow and underflow, and so on.

Here's a description of Memwatch.

Add 2: Turn from: http://www.cnblogs.com/yfanqiu/archive/2012/05/08/2490410.html

2. operator New and delete in C + +

New and delete are operators in C + +, not library functions, do not require library support, and they are encapsulated operators.

(1) New is an operator that dynamically allocates memory, automatically calculates the space to allocate , and when allocating memory space of a class type, invokes the class's constructor , initializing the memory space , which completes the initialization of the class. Dynamically assigned built-in types are automatically initialized depending on where the variable is defined, the variables defined outside the function body are initialized to 0, and the built-in type variables defined in the function body are not initialized.

(2) Delete is the memory operator that revokes the dynamic request. Delete is usually paired with new, which, in contrast to new, can revoke memory in a variety of data types, including classes, revoking the memory space of a class, calling its destructor , completing the cleanup, and reclaiming the appropriate memory resources.

(3) Typical usage

int *p = new int; Delete p;

Char *p = new char; Delete p;

The type of the class *p = the type of the new class; Delete p;

//Note that the pointer p is stored in the stack, and the memory space pointed to by P is in the heap.

OBJ * p = new obj[100]; delete []p;

Note that the new application array, delete delete form requires parentheses "[]", representing the operation of the array space, in short, the form of the application, the form of release.

(4) Memory description. The memory that the new application applies to is also stored in the heap , so the delete is required for manual recall when it is not needed.

3. The connection and difference between New/delete and Malloc/free

(1) links between Malloc/free and New/delete

A) is stored in the same way. The memory for malloc and new dynamic requests is located in the heap. The requested memory is not automatically recovered by the operating system, and it needs to be freed by the matching free and delete.

b) In addition to data types such as classes with constructors and destructors, for general data types, such as int, char, and so on, the two groups of dynamic applications can be used in a common way, with the same effect, but in a different form.

c) Memory leaks can be checked out for malloc or new, except that new can indicate the row of that file, and malloc does not have that information.

d) Both groups need pairing, malloc with free,new with Delete, note that this is not only a habit problem, if not paired with, it is easy to cause memory leaks. At the same time, in C + +, the two groups can not be mixed with, although sometimes can be compiled, but prone to large hidden dangers.

(2) The difference between Malloc/free and New/delete

A) malloc and free return void type pointers, new and delete directly with a specific type of pointer.

b) malloc and free are functions in the C language, require library support, and New/delete is an operator in C + +, so new/delete is more efficient to execute. The use of malloc and free is preserved in C + + for the purpose of using C syntax, but it is recommended that you use both new and delete as much as possible.

c) in C + +, new is type-safe, and malloc is not. For example:

int* p = new CHAR[10]; Errors are indicated at compile time

delete []p; The array needs to be added in brackets "[]"

int* p = malloc (sizeof (char) *10); Cannot indicate error at compile time

Free (p); Only the head pointers of the freed memory are needed

d) When using new dynamic request for the memory space of a class object, the construction of the class object calls the constructor, which is equivalent to initializing the memory space. In the case of malloc dynamically requesting the memory space of the class object, it is not initialized, that is, the requested memory space is unusable because the initialization of the class is done by the constructor. The meaning of delete and free is the opposite of new and malloc.

e) You cannot use malloc and free to accomplish dynamic creation and deletion of class objects.

4. Introduction to memory allocation in a C + + program

This section is referenced in http://blog.csdn.net/sparkliang/archive/2008/12/30/3650324.aspx

(1) The Stack memory allocation operation is built into the processor's instruction set, generally using registers to access, high efficiency, but the allocated memory capacity is limited. Temporary placement of general local variables and function parameters.

(2) heap memory, also known as dynamic memory. Memory space such as malloc and new applications. The lifetime of dynamic memory is determined by the programmer himself and is very flexible to use.

(3) Global Code area: allocation from static storage area. Memory is allocated at the time of program compilation, and the entire running period of the program is present in this block. For example, global variables, static variables.

(4) Constant area: The literal constant is assigned to the literal constant area, which is released by the system at the end of the program.

(5) Code area: The code that holds the entire program, because storage is stored separately from the data and code.

Summarize:

(1) New, delete is an operator and can only be used in C + +. malloc, Free is a function that can be overridden, and can be used in C and C + +. (2) New automatically calculates the amount of space that needs to be allocated, you can call the object's constructor, and the corresponding delete invokes the corresponding destructor. malloc simply allocates memory, free simply reclaims memory, does not perform construction and destructor (3) New type security, returns a pointer to a data type, malloc non-type safe, return void pointer.

About C-language memory allocations, Malloc,free, and segment errors, memory leaks

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.