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!= ')
{
Args[i]=buf;
while (*buf!= ') && (*buf!= ' \ t ') && (*buf!= ' \ n ')) buf++;
while (*buf== ") | | (*buf== ' \ t ') | | (*buf== ' \ n '))
{
*buf = ' + '; //Note the Bank
buf++;
}
i++;
}
args[i]= ' + ';
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 the character array has fastidious
Parse (Buf,args);
EXECVP (*args,args);
return 0;
}
The definition of a character array at a point should be noted that there is no problem with code definition and initialization according to the code above, at which point the BUF address is allocated in the non-read-only area, so the *buf= ' "" in Parse (Buf,args) can be called;
Use GDB to view the stack structure at this time:
Breakpoint 1, Parse (buf=0x7fffffffe661 "b C", args=0x7fffffffe640) at parse. C:15
*buf = ' + ';
But if this is defined at this time:
char* buf= "a b C";
At this point the BUF is assigned to the constant area, "segmentation fault" appears when you call *buf= ' Buf,args ' in parse, and the reason for using GDB to see the error is:
Program received signal SIGSEGV, segmentation fault.
0x0000000000400629 in Parse (buf=0x4007f3 "B-C", args=0x7fffffffe640) at parse. C:15
*buf = ' + ';
At this point, you can see that the address area of the two allocated buf is not the same, the correct address is allocated in the non-volume area (should be in the stack area), the error is assigned in the constant area;
Character array definition issues