Small memory allocation problems

Source: Internet
Author: User

Some time ago, I went to interview a Law Enforcement interview held by a club in the school with soy sauce. I didn't expect to be stuck by a few small questions. After the interview, I worked hard for a day and finally solved those problems. It seems that it is good to go to the interview without having to do anything. At least I know where I have shortcomings. Here is a question about C language memory allocation.
Take a look at the following program:
 
1 void allocmem (char ** p)
2 {
3 char r [10] = {1 };
4 * p = r;
5}
6
7
8 int main ()
9 {
10 int I;
11 char * m = NULL;
12
13 allocmem (& m );
14 if (m)
15 {
16 for (I = 0; I <10; I ++)
17 printf ("m [% d] = % d \ n", I, m [I]);
18}
19 else
20 {
21 printf ("alloc mem failed \ n ");
22}
23
24 return 0;
25}
 
The running result is:

 
Let's look at the following program:
 
1 void allocmem (char ** p)
2 {
3 * p = malloc (10 );
4 memset (* p, 1, 10 );
5}
6
7 int main ()
8 {
9 int I;
10 char * m = NULL;
11
12 allocmem (& m );
13 if (m)
14 {
15 for (I = 0; I <10; I ++)
16 printf ("m [% d] = % d \ n", I, m [I]);
17}
18 else
19 {
20 printf ("alloc mem failed \ n ");
21}
22
23 return 0;
24}
 
The running result is:


 
The difference between the two programs is that the method for allocating memory in the allocmem () function is different. The result is that the system recycles the allocated local variable (array, that is to say, the memory allocated in this way is on the stack; instead, the memory allocated by malloc () is on the stack. After the function call is completed, it will not be recycled by the system and should be released by the programmer.

 


From lknlfy
 

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.