【问题标题】:Segmentation fault 11 with my malloc'd structs我的 malloc 结构的分段错误 11
【发布时间】:2017-10-05 08:27:01
【问题描述】:

我正在尝试从一个文本文件中读取,该文件的第一个值是文本中的条目数量。使用此值,我将创建一个 for 循环,将日期和文本分配到特定结构中,直到所有条目都放置在结构中。它还将通过每个 for 循环打印值。但是,在编译时,它会出现分段错误: 11. 请您解释一下,我不太擅长 structs 和 malloc。 提前谢谢你。

(请注意,打印的文本日期故意与我作业的文本文件中的日期不同)。

#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include"journal.h"

int main(int argc, char* argv[])
{

FILE* journal;
int i, numentries;

Entry* entries;
Entry* temp;

if (argc != 2)
{
    printf("Index required");
}

fscanf(journal, "%d", &numentries);
entries = (Entry*)malloc((numentries)*sizeof(Entry));


for(i=0; i<numentries; i++)
{
    fscanf(journal,"%2d/%2d/%4d", &entries[i].day, &entries[i].month, &entries[i].year);
    fgets(entries[i].text, 101, journal);
    printf("%4d-%2d-%2d: %s", entries[i].year, entries[i].month, entries[i].day, entries[i].text);
}

fclose(journal);
return 0;
}

我的头文件(期刊)是 ->

typedef struct {
    int day;
    int month;
    int year;
    char text[101];
}Entry;

Entry entries;

文本文件的示例如下:

2
12/04/2010
Interview went well i think, though was told to wear shoes.
18/04/2010
Doc advised me to concentrate on something... I forgot.

【问题讨论】:

  • 你没有打开journal
  • 你应该使用 fopen 方法打开文件
  • 你也忘了处理日期之后的\n,所以第一个fgets只会读取换行符。 ideone.com/9Vi9tU
  • 请检查fscanf()的返回值,确保numentries有效。 I/O 可能会失败。分配也可以写成entries = malloc(numentries * sizeof *entries);,我认为它更简单更好。 Don't cast the return value of malloc() in C.
  • do cast(来自同一个问题......) - 有双方,一方赞成(承认,多数)和可敬的少数。我的建议:阅读双方的论点并自己决定(我这样做了我确实演员...)。

标签: c pointers struct file-io malloc


【解决方案1】:

这是一个有效的最小示例:

修改:

  • 打开文件并检查是否无法打开文件
  • 更正输入格式字符串(在fscanf 中添加\n

可选的修改(程序在没有它们的情况下也可以工作):

  • malloc 中移除了演员表
  • 声明的变量在哪里使用
  • 删除了无用的变量
  • malloc 中使用sizeof(*entries) 而不是sizeof(Entry)
  • 使用sizeof(entries-&gt;text) 代替硬编码值101

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
  int day;
  int month;
  int year;
  char text[101];
}Entry;

Entry entries;

int main(int argc, char* argv[])
{
  FILE* journal = fopen("yourfile", "r");
  if (journal == NULL)
  {
    printf("Cannot not open file\n");
    return 1;
  }

  int numentries;
  fscanf(journal, "%d", &numentries);
  Entry* entries = malloc(numentries * sizeof(*entries));

  for (int i = 0; i<numentries; i++)
  {
    fscanf(journal, "%2d/%2d/%4d\n", &entries[i].day, &entries[i].month, &entries[i].year);
    fgets(entries[i].text, sizeof(entries->text), journal);
    printf("%4d-%2d-%2d: %s", entries[i].year, entries[i].month, entries[i].day, entries[i].text);
  }

  fclose(journal);
  return 0;
}

除了无法打开文件的情况外,仍然没有执行错误检查。这留给读者作为练习。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多