The "rational use" here does not mean that "the use of global arrays is reasonable", but that, when there is no way to use global variables, you can also use static global arrays as appropriate when using global arrays. The premise of using a static global array is that the owner task or module of this array has a global lifecycle. Global lifecycle refers to the same life cycle as the whole program. In addition, if a variable only needs to be used by a function such as a thread or an entry function of a task, it can be completely defined as a static local array.
For multi-task or multi-thread programs, many tasks have a global lifecycle, and these tasks may need to obtain memory resources to implement specific program logic. In this case, it is best not to use the dynamic memory allocation method for the memory used by the task, that is, do not use malloc () or the new operator in C ++ to obtain the memory from the heap, instead, it is better to use static global arrays to simplify code. Figure 1 shows the code for the thread_authenticator thread to initialize its static global variable g_aaa_eap_str_buff using malloc (). Figure 2 shows a static global array.
Example. c
# DefineMAX_PORTS64
# DefineMAX_IDS (MAX_PORTS * 256)
# DefineMAX_MSG_LEN4096
Static char ** g_aaa_eap_str_buff;
Voidthread_authenticator (void * _ arg)
{
G_aaa_eap_str_buff = (char **) malloc (MAX_IDS );
If (0 = g_aaa_eap_str_buff ){
Log_error ("Failed to allocate buffer for storing eap strings ");
Return;
}
For (int I = 0; I <MAX_IDS; I ++ ){
G_aaa_eap_str_buff [I] = (char *) malloc (MAX_MSG_LEN );
If (0 = g_aaa_eap_str_buff [I]) {
Log_error ("Failed to allocate buffer for storing eap strings ");
}
}
While (1 ){
...
}
} Figure 1
Example. c
# DefineMAX_PORTS64
# DefineMAX_IDS (MAX_PORTS * 256)
# DefineMAX_MSG_LEN4096
Static char ** g_aaa_eap_str_buff [MAX_IDS] [MAX_MSG_LEN];
Voidthread_authenticator (void * _ arg)
{
While (1 ){
...
}
} Figure 2
When arrays are used, the memory space is allocated to the. bss or. data segments during compilation, depending on whether the array is initialized. In this way, it is natural to save the call to the malloc () function, and of course there is no judgment on its return value.
In addition to the thread-related memory, which can be implemented using a global static array, there are many other scenarios where you can consider using static global or local arrays to simplify code, such:
1) For a telecom device supporting 0.2 million users, the data structure memory required by each user can be considered to be allocated in advance using a static global or partial) array, instead of using malloc () for temporary allocation from the heap for every access user.
2) for software modules with a global lifecycle, you can also consider using static global or local) arrays as the memory required.
This article from "to Jane Li cloud" blog, please be sure to keep this source http://yunli.blog.51cto.com/831344/247388