Character array definition problem, character array Definition

Source: Internet
Author: User
Tags array definition

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;

 

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.