简体   繁体   English

我尝试运行此程序时出现段错误错误

[英]Segmentation fault error when I try to run this program

#include <stdio.h>
#include <stdlib.h>
#include "vettore.h"

int main(int argc, char *argv[]){
    if(argc != 5)
        printf("Incorrect parameters number\n");
    else{
        int n = atoi(argv[1]);
        int *a = (int*) calloc(n, sizeof(int));
        if(a == NULL)
            printf("Unsufficient memory\n");
        else{
            finput_array(argv[2], a, n);
            bubblesort(a, n);
            foutput_array(argv[4], a, n);
            int *oracle = (int*) calloc(n, sizeof(int));
            finput_array(argv[3], oracle, n);

            if(compare_array(a, oracle, n))
                printf("PASS\n");
            else
                printf("FAIL\n");
        }
    }
}

I run the program this way: ./test_ordina_array.exe 12 TC4_input.txt TC4_oracle.txt TC4_output.txt but it gives me segmentation fault. 我以这种方式运行程序: ./test_ordina_array.exe 12 TC4_input.txt TC4_oracle.txt TC4_output.txt但它给我分段错误。

"TC4_output.txt" is created by the program while the other two files already exist. 该程序创建了“ TC4_output.txt”,而另外两个文件已经存在。

This are the functions used: 这些是使用的功能:

    void bubblesort(int a[], int n){
int i, j;
  for(i = 0 ; i < n - 1; i++)
  {
    for(j = 0 ; j < n - i - 1; j++)
    {
      if (a[j] > a[j+1]) /* For decreasing order use < */
      {
        swap(&a[j], &a[j+1]);
       }
      }
     }
}

void finput_array(char *file_name, int a[], int *n){
    FILE *fd = fopen(file_name, "r");
    if(fd == NULL)
        printf("Errore in apertura del file %s\n", file_name);
    else{
        int i = 0;
        fscanf(fd, "%d", &a[i]);
        while(i<*n && !feof(fd)){
            i++;
            fscanf(fd, "%d", &a[i]);
        }
        fclose(fd);
        if(i<*n)
            *n = i;
    }
}

void foutput_array(char *file_name, int a[], int n){
    int i;
    FILE *fd;

    fd = fopen(file_name, "w");
    if(fd == NULL)
        printf("Errore in apertura del file %s\n", file_name);
    else{
        for(i=0; i<n; i++)  
            fprintf(fd, "%d\n", a[i]);
        fclose(fd);
    }
}

int compare_array(int a[], int b[], int n){
    int i=0;

    while(i<n && a[i] == b[i])
        i++;

    return (i==n) ? 1 : 0;
}

They are contained in "vettore.c" and "vettore.h" contains their prototypes. 它们包含在“ vettore.c”中,“ vettore.h”包含其原型。

The program has to order in ascending order the elements contained in the first txt file and write them in the output file. 程序必须按升序对第一个txt文件中包含的元素进行排序,并将它们写入输出文件中。

You have problem when using finput_array 使用finput_array时遇到问题

finput_array(argv[2], a, n);

Please replace by 请替换为

finput_array(argv[2], a, &n);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM