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