【问题标题】:Bus error when allocating data of structs to an array and then Writing to a .txt file将结构数据分配给数组然后写入 .txt 文件时出现总线错误
【发布时间】:2015-02-17 05:24:33
【问题描述】:

所以对于我的课堂作业,我们应该提示用户输入员工的数量(比如 5 个),然后提示他们输入每个员工的数据(姓名、薪水和部门),然后将指向员工数据的指针存储在数组中。输入完成后,程序应打印数据并将其写入文本文件。所以由于某种原因,当我运行函数 ./employees 时,我得到“总线错误”。任何线索为什么?如果您需要我澄清任何事情,请告诉我。代码如下:

#include <stdio.h>
#include <string.h> 
#include <stdlib.h>
#include "struct.h"
#include "employees.h"
#include <readline/readline.h>
#include <readline/history.h>
#include <errno.h>

#define MAXLINE (100) // MAXLINE is maximum length of an input line.

int main() {
  char* inputline; // pointer to input line
  char name[MAXLINE];
  int salary;
  char empSalary[MAXLINE]; 
  char department[MAXLINE];
  int num; // Number of employees
  int i; // Loop counter
  char* employeeArray[num*3];
  FILE *outfile = fopen("employee.txt", "w"); // Open or create file for writing

  inputline = readline("Enter the total number of employees: "); // Read the input line.
  num = atoi(inputline);

  for (i = 1; i < num + 1; i++) {
    struct _Employee* emp = malloc(sizeof(struct _Employee));

    inputline = readline("Enter the name of the employee: "); // Read the input line
    sscanf(inputline, "%s", name); // reads formatted input from a string.

    inputline = readline("Enter the salary of the employee: "); // Read the input line

    if (sscanf(inputline, "%s", salary) == 1) {
      printf("Invalid salary. Try again!\n"); // Error message for if the salary is less than 0
      inputline = readline("Enter the salary of the employee: "); // Read the input line
      salary = atoi(inputline); // Converts inputline to an integer and sets salary to that value.
    }

    salary = atoi(inputline); // Converts inputline to an integer and sets salary to that value.

    if (salary < 0) {
      printf("Invalid salary. Try again!\n"); // Error message for if the salary is less than 0
      inputline = readline("Enter the salary of the employee: "); // Read the input line
      salary = atoi(inputline); // Converts inputline to an integer and sets salary to that value.
    }

    inputline = readline("Enter the department of the employee: "); // Read the input line
    sscanf(inputline, "%s", department); // reads formatted input from a string

    emp->name = strdup(name);
    emp->salary = salary;
    emp->department = strdup(department);

    sprintf(empSalary,"%d", salary);

    employeeArray[(i*3) - 3] = name; 
    employeeArray[(i*3) - 2] = empSalary;
    employeeArray[(i*3) - 1] = department;

    printEmployee(emp);

    printf("About to write to file.\n");

    if (outfile == NULL) {
      printf("[employee] %d The open was unsuccessful!\n", errno, strerror(errno));
      return 1;
    }

    else {
      outputData(outfile, name, empSalary, department);
    }
  }

  fclose(outfile);

  freeMemory(*employeeArray);
}

/* Writes the input data to a text file employee.txt
 * @param stream The file to be written to
 * @param name Name of the employee
 * @param empSalary Salary of the employee
 * @param department Department the employee works in
 */

void outputData(FILE *stream, char* name, char* empSalary, char* department) {
  FILE *outfile = fopen("employee.txt", "w"); // Open or create file for writing

  fprintf(outfile, "%s\n %s\n %s\n", *name, *empSalary, *department);
}

/* Frees the memory of the array
 * @param array The array to be de-allocated
 */

void freeMemory(char* array) {
  int i; // Loop counter

  for (i = 0; i < sizeof(array); i++) {
    free(&array[i]);
  }
}

【问题讨论】:

    标签: c arrays


    【解决方案1】:

    我看到以下问题:

    freeMemory 中,您正在尝试释放未使用适当函数(malloccallocrealloc)分配的内存。

    malloc曾经为struct _Employee分配内存,但是array中存储的指针(freeMemory的参数)显然不是指向_Employee的指针

    而且使用免费的 as

     free(&array[i]);
    

    看起来本身是错误的 - 你得到了元素的地址(可能不是第一个 - 即使array 的地址来自类似malloc( N * sizeof(char)) 调用free(&amp;array[i])i &gt; 0 导致内存管理错误(@ 987654335@ 可以,并且仅当内存已分配且之前未取消分配,并且发送到 free 的地址必须与从 malloc 接收到的地址相同时。

    编辑

    唯一的解决方案可以提供帮助 - 重新设计程序(或者更好地说,在编码之前设计程序)。祝你好运!

    【讨论】:

      【解决方案2】:

      在 outputData() 中,给出 fprintf() 的指针:

      fprintf(outfile, "%s\n %s\n %s\n", name, 
          empSalary, department);
      

      编辑:哦!似乎这里和那里的错误更多:

      • freeMemory() 中:sizeof(array) 是指针的大小(4 或 8),而不是数组容量。
      • 请致电freeMemory(employeeArray) 而不是freeMemory(*employeeArray)
      • 您不能释放静态(堆栈上)指针:name、empSalary 和 depatment 不是动态的。但是,emp 的属性
      • 更好的是,删除无用的freeMemory() 函数。
      • 不幸的构造混合结构和(错误的)二维字符串数组。
      • 许多其他东西...

      作为一个很好的练习(和建议!):从你的代码中删除employeeArray,它会变得更清晰。

      我还会删除 emp 的 malloc() 以坚持静态结构和 使用后正确释放emp.nameemp.department,然后再循环。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-23
        • 2021-04-03
        • 2017-02-17
        • 1970-01-01
        • 1970-01-01
        • 2021-06-09
        • 1970-01-01
        • 2021-11-08
        相关资源
        最近更新 更多