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

标签 c unix memory codeblocks

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/

相关文章:

c - 在 Hp-UX ksh 中执行交互式命令(意外)并获取子进程

java - 如何启动具有更多内存的 Java 小程序?

memory - R XML 包中的 htmlParse() 段错误错误 : 'memory not mapped'

c - 从 C 函数返回局部变量

c - getc(stdin) 后程序停止工作

unix - 目录的平均大小和最大大小

c - 主存中的程序元素

c - 为什么删除和重命名函数在我的程序中不起作用?

c - 在 Windows 中移动 TreeView 项目

scala - 为什么 Scala Range 迭代器会缓冲——有时?