Segmentation fault error when I try to run this program - c

#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.
"TC4_output.txt" is created by the program while the other two files already exist.
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.
The program has to order in ascending order the elements contained in the first txt file and write them in the output file.

You have problem when using finput_array
finput_array(argv[2], a, n);
Please replace by
finput_array(argv[2], a, &n);

Related

Why doesn't this program write in result.txt?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vettore.h"
int main(int argc, char *argv[]){
FILE *result = fopen("result.txt", "w");
int cont = 0, i, n;
char *s1;
if(argc != 1)
printf("Numero parametri non corretto\n");
else{
FILE *fp = fopen("test_suite.txt", "r");
while(fscanf(fp, "%s %d", s1, &n) == 2)
cont++;
rewind(fp);
for(i=0; i<cont; i++){
fscanf(fp, "%s %d", s1, &n);
int *a = (int*) calloc(n, sizeof(int));
char *s2;
strcpy(s2, s1);
finput_array(strcat(s1,"_input.txt"), a, n);
strcpy(s1,s2);
bubblesort(a, n);
foutput_array(strcat(s1, "_output.txt"), a, n);
strcpy(s1,s2);
int *oracle = (int*) calloc(n, sizeof(int));
finput_array(strcat(s1, "_oracle.txt"), oracle, n);
strcpy(s1,s2);
if(confronta_array(a, oracle, n))
fprintf(result, "%s PASS\n", s1);
else
fprintf(result, "%s FAIL\n", s1);
free(a);
free(oracle);
}
fclose(fp);
}
fclose(result);
}
This are "vettore.c" functions:
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 < */
{
scambia(&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{
for(int i=0; i<n; i++)
fscanf(fd, "%d", &a[i]);
fclose(fd);
}
}
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 confronta_array(int a[], int b[], int n){
int i=0;
while(i<n && a[i] == b[i])
i++;
return (i==n) ? 1 : 0;
}
The program doesn't write anything in "result.txt". Why?
It should write those sentences.
In this part:
while(fscanf(fp, "%s %d", s1, &n) == 2) cont++;
Maybe "cont" dont increment because "test_suite.txt" don't have the "fscanf" format requirements.

Storing numbers as (x, y) cordinates from a file at a specific point

I have an Instance File from which I need to store the NUM_PT and all the respective co-ordinates in the form of a 2D array system (personal choice so I can access them easily). I am able to retrieve the NUM_PT but I am stuck at reading the successive cordinates into my array.
HERE IS WHAT I HAVE DONE
/* Assignment 2 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define MAXS 256
int main(int argc, char *argv[])
{
int num_pt;
int inputfile = 0, outputfile = 0, i;
for (i = 1; i < argc; i++)
{
if (strcmp (argv[i], "-i") == 0)
inputfile = i+1;
if (strcmp (argv[i], "-o") == 0)
outputfile = i+1;
}
if (inputfile == 0)
{
/* invalid command line options */
printf("\nIncorrect command-line...\n");
printf("> %s [-i inputfile [-o outputfile]]\n\n", argv[0]);
exit(0);
}
FILE *fp;
fp = fopen(argv[inputfile], "r");
int count = 0;
if (fp == 0)
{
printf("\nCould not find %s\n", argv[inputfile]);
exit(0);
}
char line[MAXS];
while (fgets(line, sizeof line, fp) != NULL)
{
if (count == 4)
{
fscanf(fp, "%d", &num_pt);
break;
}
else
count++;
}
int arr[num_pt][1];
while (fgets(line, sizeof line, fp) != NULL)
{
if (count == 5)
{
int k, j, cord;
for (k = 0; k < num_pt; k++)
{
for (j = 0; j < num_pt; j++)
{
while (fscanf(fp, "%d%d", &cord) > 0)
{
arr[k][j] = cord;
j++;
}
}
}
}
}
fclose(fp)
return 0;
}
After retrieving NUM_PT i tried reinitializing the count to 5 because the cordinates start from **LINE 6* in the file.
ERROR FROM COMPILER
Language: c99 ; Compiler: gcc
sample for "Storing numbers as (x, y) cordinates from a file" (It is better not to fix the reading position)
#include <stdio.h>
typedef struct point {
int x, y;
} Point;
int readPoint(FILE *fp, Point *p);
int readInt(FILE *fp, int *n);
int main(void){
FILE *fp = fopen("instance10_001.txt", "r");
Point p;
int MAX_X, MAX_Y;
readPoint(fp, &p);
MAX_X = p.x;
MAX_Y = p.y;
printf("MAX_X:%d, MAX_Y:%d\n", MAX_X, MAX_Y);
int NUM_PT;
readInt(fp, &NUM_PT);
printf("NUM_PT:%d\n", NUM_PT);
Point arr[NUM_PT];
for(int i = 0; i < NUM_PT; ++i){
readPoint(fp, &arr[i]);
printf("Point(%d, %d)\n", arr[i].x, arr[i].y);
}
fclose(fp);
}
int readLine(FILE *fp, char *buff, int buff_size){
while(fgets(buff, buff_size, fp)){
if(*buff == '#' || *buff == '\n')
continue;
return 1;
}
return 0;
}
#define LINE_MAX 128
int readPoint(FILE *fp, Point *p){
char buff[LINE_MAX];
if(readLine(fp, buff, sizeof buff)){
return 2 == sscanf(buff, "%d %d", &p->x, &p->y);
}
return 0;
}
int readInt(FILE *fp, int *n){
char buff[LINE_MAX];
if(readLine(fp, buff, sizeof buff)){
return 1 == sscanf(buff, "%d", n);
}
return 0;
}

Arrays being randomly overwritten in C program. Probably simple solution

I have 4 functions that run through a text file and store the values to their designated arrays decalred at the beginning of the problem. The issue i'm having is that when I update one of the arrays the others all are never updated or are reset. So for example if I run the getkosDS function it will update the array and print out the value i am looking for. The other arrays will contain zero. However if I comment out the getkosDS function the next array (nipsDS) will update and not be zero!!! I am very confused.
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int kosND;
int kosNW;
int kosNZC;
int enronND;
int enronNW;
int enronNZC;
int nipsND;
int nipsNW;
int nipsNZC;
int nytND;
int nytNW;
int nytNZC;
int world_size;
int my_rank;
int kosDS[3430];
int nipsDS[1500];
int enronDS[39861];
int nytDS[300000];
void getKOS(){
int i;
FILE *MyFile;
char line[25];
MyFile=fopen("/home/mcconnel/BagOfWords/docword.kos.txt","r");
for(i=0; i<5; i++){
fscanf(MyFile, "%s", line);
if(i == 0){
kosND = atoi(line);
}
if(i == 1){
kosNW = atoi(line);
}
if(i == 2){
kosNZC = atoi(line);
}
}
fclose(MyFile);
}
void getEnron(){
int i;
FILE *MyFile;
char line[25];
MyFile=fopen("/home/mcconnel/BagOfWords/docword.enron.txt","r");
for(i=0; i<5; i++){
fscanf(MyFile, "%s", line);
if(i == 0){
enronND = atoi(line);
}
if(i == 1){
enronNW = atoi(line);
}
if(i == 2){
enronNZC = atoi(line);
}
}
}
void getNips(){
int i;
FILE *MyFile;
char line[25];
MyFile=fopen("/home/mcconnel/BagOfWords/docword.nips.txt","r");
for(i=0; i<5; i++){
fscanf(MyFile, "%s", line);
if(i == 0){
nipsND = atoi(line);
}
if(i == 1){
nipsNW = atoi(line);
}
if(i == 2){
nipsNZC = atoi(line);
}
}
fclose(MyFile);
}
void getNYT(){
int i;
FILE *MyFile;
char line[25];
MyFile=fopen("/home/mcconnel/BagOfWords/docword.nytimes.txt","r");
for(i=0; i<5; i++){
fscanf(MyFile, "%s", line);
if(i == 0){
nytND = atoi(line);
}
if(i == 1){
nytNW = atoi(line);
}
if(i == 2){
nytNZC = atoi(line);
}
}
fclose(MyFile);
}
void getKosDS(){
int i;
int z;
FILE *MyFile;
char line[25];
MyFile=fopen("/home/mcconnel/BagOfWords/docstart.kos.txt","r");
for(i = 0; i<3430; i++){
fscanf(MyFile, "%s", line);
if(i != 0 && i % 2 == 1){
kosDS[z] = atoi(line);
z++;
}
}
fclose(MyFile);
}
int getNipsDS(){
int i;
int z;
FILE *MyFile;
char line[25];
MyFile=fopen("/home/mcconnel/BagOfWords/docstart.nips.txt","r");
for(i = 0; i<1500; i++){
fscanf(MyFile, "%s", line);
if(i != 0 && i % 2 == 1){
nipsDS[z] = atoi(line);
z++;
}
}
fclose(MyFile);
}
int main(int argc, char** argv)
{ MPI_Init(NULL,NULL);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
// printf("\n%d", world_size);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
// printf("\n%d", my_rank);
if(my_rank == 0){
getKOS();
getEnron();
getNips();
getNYT();
getKosDS();
// getEnronDS();
// getNytDS();
printf("\ngetting complete\n");
printf("KOS location %d\n", kosDS[5]);
// printf("Enron location %d\n", enronDS[200]);
printf("Nips location %d\n", nipsDS[500]);
// printf("NYT location %d\n", nytDS[10000]);
}
else{
printf("\n%d \n", my_rank);
}
MPI_Finalize();
}
this is the result
KOS location 4875
Nips location 0
however if I were to comment out getKosDS the result is
KOS location 0
Nips location 28340
Craziness, if you can't tell I'm new to C
In getKosDS the z is uninitialized, so by writing to nipsDS[z] you are actually writing into a random memory location, invoking an undefined behavior.
Update:
The same problem is in the getNipsDS function.

C: Sort Comma Delimited List of Numbers in a file

I need to sort a list of numbers in a file in a ascending order. I have done all the opening of the file and created my bubble sort function. But I'm stuck on how to make this all work together.
my inputefile.csv looks something like the following:
3,-4,-5,-8
10,30,50,-10
40,100,60,-2
void bubble_sort(char* line, int size);
int main(void)
{
FILE *file;
char* line;
int size = sizeof(line);
file = fopen("inputfile.csv", "r");
if(file == NULL)
{
printf("Unable to open the file");
}else
{
while(fgets(line, sizeof(line), file)
{
bubble_sort(line, size)
}
}
}
void bubble_sort(char* line, int size)
{
int temp, i, j;
for (i=0; i< size-1; i++)
{
for (j=0; j<size-1; j++)
{
if(line[j] > line[j+1])
{
temp = line[j];
line[j] = line[j+1];
line[j+1] = temp;
}
}
}
}
The number of lines is unknown and also each line has 4 integers separated by a comma. By my code you could say i am a newbee
#include <stdio.h>
#include <stdlib.h>
void bubble_sort(int *array, int size);
int main(void){
FILE *file;
char line[128];
if((file = fopen("inputfile.csv", "r")) == NULL){
printf("Unable to open the file");
return -1;
}
while(fgets(line, sizeof(line), file)){
int i, a[4], size = sizeof(a)/sizeof(*a);
sscanf(line, "%d,%d,%d,%d", &a[0], &a[1], &a[2], &a[3]);
bubble_sort(a, size);
for(i = 0; i < size; ++i){
printf("%d", a[i]);
if(i<size-1)
printf(", ");
}
printf("\n");
}
fclose(file);
return 0;
}
void bubble_sort(int *a, int size){
int i, temp, swap;
do{
for(swap=i=0;i<size-1;++i){
if(a[i]>a[i+1]){
swap = 1;
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
--size;
}while(swap);
}

Reading a dynamic array from a file with function

I have the following code:`
#include <stdio.h>
#include <stdlib.h>
void load_from_file(int A[], int *n);
int main()
{
int *A;
A = (int*)malloc(0);
int count = 0;
int i;
load_from_file(A, &count);
for(i = 0; i < count; i++)
{
printf("A[%d]=%d ", i, A[i]);
printf("\n");
printf("&A[%d]=%p \n\n", i, &A[i]);
}
return 0;
}
void load_from_file(int A[], int *n)
{
FILE* fp;
int temp, i;
fp = fopen("data.txt", "r");
if (fp == NULL)
{
printf("error!!");
exit (1);
}
fscanf(fp, "%d", &temp);
*n = temp;
A = (int*) realloc(A, temp * sizeof(int));
if (*A == NULL)
{
printf("error realloc!!");
exit(1);
}
for(i = 0; i < temp; i++)
{
fscanf(fp, "%d", &A[i]);
}
for(i = 0; i < temp; i++)
{
printf("A[%d]=%d ", i, A[i]);
printf("\n");
printf("&A[%d]=%p \n\n", i, &A[i]);
}
fclose(fp);
}
I'm trying to read a text file into an array.
First line of the file has the number of elements of the array, and second line the numbers-elements.
We create the array through realloc.
But something is going wrong.....
I have some patches, printing the address of array's elements.
But unfortunatelly they are different(not all the times) inside the function, and outside the function, although an array is passed by reference (as I think...)
Please, tell me where is the mistake, and how can I fix the problem.
Thanks in advance...
Dimitri
Call:
int *A = load_from_file(&count);
Function:
int *load_from_file(int *n)
{
FILE* fp;
int temp,i;
int *A = 0;
fp=fopen("data.txt","r");
if (fp==NULL){fprintf(stderr, "error!!\n");exit (1);}
fscanf(fp,"%d",&temp);
*n=temp;
A = (int*) realloc(A,temp * sizeof(int));
if (A == NULL) {fprintf(stderr, "error realloc!!\n");exit(1);}
for(i=0;i<temp;i++)
fscanf(fp, "%d",&A[i]);
for(i=0;i<temp;i++)
{
printf("A[%d]=%d ",i,A[i]);
printf("\n");
printf("&A[%d]=%p \n\n",i,&A[i]);
}
fclose(fp);
return A;
}
This is a totally minimal set of changes; the code needs a lot more work. In particular, the fscanf() calls should be error checked. There's a subtle but important change in the allocation test: if (A == NULL) rather than the original if (*A == NULL).
With somewhat more complete error checking:
int *load_from_file(int *n)
{
FILE *fp;
int temp, i;
int *A = 0;
const char file[] = "data.txt";
fp = fopen(file, "r");
if (fp == NULL)
{
fprintf(stderr, "Failed to open file %s for reading\n", file);
exit(1);
}
if (fscanf(fp, "%d", &temp) != 1)
{
fprintf(stderr, "Failed to read number of entries\n");
exit(1);
}
*n = temp;
A = (int *) realloc(A, temp * sizeof(int));
if (A == NULL)
{
fprintf(stderr, "Failed to reallocate %zu bytes of memory\n",
temp * sizeof(int));
exit(1);
}
for (i = 0; i < temp; i++)
{
if (fscanf(fp, "%d", &A[i]) != 1)
{
fprintf(stderr, "Failed to read entry number %d\n", i);
exit(1);
}
}
for (i = 0; i < temp; i++)
printf("A[%d]=%d: &A[%d]=%p\n", i, A[i], i, &A[i]);
fclose(fp);
return A;
}
I have a library of error reporting functions that I use which would reduce the error handling from 4 lines to 1 line per error. I strongly recommend creating and using such a library for yourself.

Resources