gpt4 book ai didi

c - strcpy 中的段错误或与读取某个变量有关的任何事情

转载 作者:太空宇宙 更新时间:2023-11-04 06:16:48 24 4
gpt4 key购买 nike

char *multi_tok(char *input, int *type) {
static char *string;
if (input != NULL)
string = input;

if (string == NULL)
return string;

char *end=NULL;
for(int i=0; *(string+i+1) != 0; i++)
{
if( *(string+i) == '|')
{
*type=0;
end=(string+i);
break;
}else if( *(string+i) == '<')
{
*type=1;
end=(string+i);
break;
}else if( *(string+i) == '>' && *(string + i + 1) == '>'){
*type=2;
end=(string+i);
break;
}
else if( *(string+i) == '>'){
*type=3;
end=(string+i);
break;
}
}
if(end==NULL)
{
char *temp=string;
string =NULL;
return temp;
}
*end='\0';
char *temp;
temp=malloc(sizeof(char)*strlen(string));
strcpy(temp, string);
int d=(*type != 2) ? 2 : 3 ;
string=end + d;
return temp;
}


int main (int argc, char* argv [])
{
char cmdline[BUFSIZ];
for(;;) {
printf("COP4338$ ");
if(fgets(cmdline, BUFSIZ, stdin) == NULL) {
perror("fgets failed");
exit(1);
}
int *type;
char *str= multi_tok(cmdline, type);
int i=0;
char str_c[1024];
while (str != NULL) {
strcpy(str_c, str);
str = multi_tok(NULL, type);
}
}
}

分割发生在:

while (str != NULL) {
strcpy(str_c, str);
str = multi_tok(NULL, type);
}
}

或几乎与读取变量 str 有关的任何事情,即使我不使用 strcpy 和手动循环来复制字符串段错误也会以任何方式发生。但是,如果我构建一个函数来复制它的字符串,例如:

char *copy(char *str)
{
char *str2=(char*)malloc(sizeof(char)*strlen(str));
strcpy(str2, str);
return str2;
}
...
while (str != NULL) {
str_c=copy(str);
str = multi_tok(NULL, type);
}
}
...
//works

为什么会这样?

最佳答案

type 没有分配任何内存给它,所以分配 *type=0 会导致可能的分段失败

关于c - strcpy 中的段错误或与读取某个变量有关的任何事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43691436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com