Character array definition problem, character array Definition
The problem code is as follows:
# Include <unistd. h>
# Include <string. h>
# Include <stdio. h>
Void parse (char * buf, char * args [])
{
Printf ("buf = % s \ n", buf );
Int I = 0;
While (* buf! = '\ 0 ')
{
Args [I] = buf;
While (* buf! = '') & (* Buf! = '\ T') & (* buf! = '\ N') buf ++;
While (* buf = '') | (* buf = '\ t') | (* buf =' \ n '))
{
* Buf = '\ 0'; // pay attention to this row
Buf ++;
}
I ++;
}
Args [I] = '\ 0 ';
Int j = 0;
While (j <I)
{
Printf ("arg [% d] = % s \ n", j, args [j]);
J ++;
}
Return;
}
Int main ()
{
Char * args [4];
Char buf [100] = "a B c"; //-1-here the definition of character arrays is exquisite
Parse (buf, args );
Execvp (* args, args );
Return 0;
}
-1-when defining character arrays, you must note that there is no problem with initialization according to the Code definition in the above Code. In this case, the buf address is allocated to the non-read-only zone, therefore, you can call * buf = '\ 0' in parse (buf, args ';
Use gdb to view the stack structure:
Breakpoint 1, parse (buf = 0x7fffffffe661 "B c", args = 0x7fffffffe640) at parse. C: 15
15 * buf = '\ 0 ';
However, if the definition is as follows:
Char * buf = "a B c ";
At this time, the buf is allocated in the constant area. When * buf = '\ 0' in the call to parse (buf, args), "Segmentation fault" appears ", check the cause of the Error Using gdb:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400629 in parse (buf = 0x4007f3 "B c", args = 0x7fffffffe640) at parse. C: 15
15 * buf = '\ 0 ';
At this point, we can see that the address regions of the two allocated buckets are different. The correct address is allocated in the extraordinary volume area (which should be in the stack area) and allocated in the constant area when an error occurs;