c - 家庭作业的段错误。不知道为什么

标签 c struct segmentation-fault

我无法找出段错误的原因。我已经在 GDB 中进行了调试,它告诉我是哪一行给我带来了麻烦,但我仍然无法弄明白。

Employee* readfile(FILE* file) {
  Employee* newemployee;
  char* tempsalary;
  int salary;
  char* name;
  char* dept;
  char line[128];
  while(file != NULL) {
    fgets(name, sizeof(line), file);
    newemployee->name = strdup(name);  // THIS IS WHERE THE SEGFAULT IS
    fgets(dept, sizeof(line), file);
    newemployee->department = strdup(dept);
    fgets(tempsalary, sizeof(line), file);
    sscanf(tempsalary, "%d", &salary);
    newemployee->salary = salary;
  }
  return newemployee;

我尝试在其中运行它的主程序应该打开文件、读取行并从中创建一个 Employee 结构。它使用先前的函数打印结构。

int main() {
  FILE* file;
  file = fopen ("stest2.txt", "r");
  Employee* employees[max_employees];
  int i;
  int c;

  for (i = 0; i < max_employees; i++) {
    employees[i] = readfile(file);
    printEmployee(employees[i]);
  }

}

最佳答案

你好像打错了,你的意思是:

fgets(name, sizeof(line), file);

成为:

fgets(line, sizeof(line), file);

此外,

Employee* newemployee;
newemployee->name = strdup(name);

您刚刚取消引用了一个未初始化的指针,导致了未定义的行为
newemployee 需要指向一个足够大的内存来容纳 Employee 对象,然后才能取消引用它。

Employee* newemployee;
Employee emp;
newemployee = &emp;
newemployee->name = strdup(name);

上述两个问题都在您的代码中重复出现。你需要解决这个问题。

关于c - 家庭作业的段错误。不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14825151/

相关文章:

xcode - 在 Swift 中使用结构时如何简洁地定义模型对象?

Ruby/Watir - browser.close 上的段错误

Python 3 C扩展导入时出现段错误

android - 将 SDL C++ 应用程序交叉编译到 Android

database - Golang DB反/序列化方法(数据库/sql之上的sqlx)

c - 删除<img></img>标签的内容

c - 使用 Structs 来保存我在 C 游戏中的所有变量?

c - 如何使 putenv 成为可重入函数?

c 字符串比较 vs 哈希比较

c - hiredis 报错 1 REDIS_ERR_IO 没有那个文件或目录