Comparison of dynamic memory space initialization Methods

Source: Internet
Author: User

Comparison of dynamic memory space initialization Methods
1. initialize the SDK using the following method;
2. initialize by moving the pointer;

 
******************/ # Include <stdio. h> # include <stdlib. h> int main (void) {int * P = (int *) malloc (5 * sizeof (INT); printf ("this is the subscript method initialization method: \ n "); for (INT I = 0; I <5; I ++) {P [I] = I + 1; printf ("% d \ t ", P [I]);} Free (p); Return 0 ;}
 
****************** /# Include <stdio. h> # include <stdlib. h> int main (void) {int I; int * P = (int *) malloc (5 * sizeof (INT); printf ("this is initiated by moving the pointer: \ n "); int * Pv = P; for (I = 0; I <5; I ++) {* Pv = I + 1; printf ("% d \ t", * PV); PV ++;} Free (p); Return 0 ;}

both methods can initialize the dynamically applied memory space, however, it is obvious that the first method (subscript method) is more convenient and safer than the second method (move pointer method. Cause: In the second method (move pointer mode), if you move the defined pointer variable directly, when the memory space is finally released, you may forget to move the pointer position to the initial position (this method is not recommended, of course), and directly pass the pointer to free (void * pointer) to release the space. However, at this time, the pointer position has changed and is no longer the first address of the memory space. Therefore, runtime errors will occur when the memory is released. To solve this problem, we need to define a temporary pointer variable to point to the position pointed to by the original pointer, and then use this temporary pointer variable to initialize the memory space, finally, pass the original pointer to free (void
* pointer) to release the memory space.
I think it is better to use the subscript method to initialize the dynamically applied memory space!

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.