Character array definition issues

Source: Internet
Author: User
Tags 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!= ')
{
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

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.