【问题标题】:strtok getting segmentation error read filestrtok获取分段错误读取文件
【发布时间】:2013-09-30 02:22:36
【问题描述】:

在 strtok 上出现分段错误,我将输入字符串 lyne 定义为 char 数组而不是指针,但似乎不起作用。这是在 C 和 linux 中

    typedef struct 
    {
    int x;
    char *y;
    } child;

    typedef struct{
    child *details;
    }  parent;


        fp = fopen(filename,"r"); // read mode
        char lyne[25];
        char *item;
    fgets(lyne,25,fp);  

    parent record;
        record.details= malloc (5  * sizeof(child));    

        while (fgets(lyne,25,fp)) {

            printf("test %s \n",lyne);

            item = strtok(lyne," ");    

strcpy(record.details->y,item);//seg error on this line
        }
        fclose(fp);


my file looks like this
file#1
ABC 100
BCE 200


OUTPUT:
test ABC 100

Segmentation fault

【问题讨论】:

  • @jxh:如果没有产生输出,你认为printf 调用在做什么?
  • Works for me。问题必须在其他地方,在你没有显示的代码中。
  • @jxh:这正是 OP 所显示的。跳过“file#1”行;输出从第二行开始。
  • @IgorTandetnik:我完全不清楚“file#1”是输入的一部分。既然你这么说,我会在这一点上让提问者受益。
  • strcpy 的第一个参数应该指向一个足够大的有效缓冲区。 record.details->y 未初始化,包含垃圾,指向内存中的某个随机地址。

标签: c++ c linux


【解决方案1】:

您尚未将内存分配给结构子成员“y”,因为您的结构是

typedef struct 
    {
    int x;
    char *y;
    } child;

你要做的是:

record.details->y = malloc(sizeof(char)*(strlen(item) + 1));
strcpy(record.details->y,item);

【讨论】:

    【解决方案2】:

    必须添加 parent.deatils->y = (char *) malloc(24);使用前

    【讨论】:

      猜你喜欢
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      相关资源
      最近更新 更多