//this is extlcs.c
#include <stdio.h>
#include <stdlib.h>
#include "extlcs.h"
typedef struct {
long long *row;
long nRow;
long long *col;
long nCol;
}ttable;
int Max(int a, int b){
if(a>b) return a;
else return b;
}
int calcLcs(const long long *row, long Nrow, long Ncol, const long long *col){
int matrix[Nrow+1][Ncol+1];
int i,j;
for(i=0;i<Nrow;i++){
matrix[i][0]= 0 ;
}
for(j=0;j<Ncol;j++){
matrix[0][j] = 0;
}
for(i=1;i<Nrow;i++){
for(j=1;j<Ncol;j++){
if(row[i-1]==col[j-1]) matrix[i][j] = matrix[i-1][j-1] + 1;
else matrix[i][j] = Max(matrix[i][j-1],matrix[i-1][j]);
}
}
printf("%d", matrix[i][j]);
return matrix[i][j];
}
int extlcs(char *input1, char *input2, char *output) {
FILE *prova1 = fopen(input1, "r");
FILE *prova2 = fopen(input2, "r");
ttable *table = (ttable*) malloc(sizeof(ttable));
fseek(prova1,0L,SEEK_END);
table->nRow = ftell(prova1);
fseek(prova1, 0L, SEEK_SET);
printf("%ld\n", table->nRow);
table->row = 0;
table->row = (long long*) malloc(table->nRow);
fseek(prova2,0L,SEEK_END);
table->nCol = ftell(prova2);
fseek(prova2, 0L, SEEK_SET);
printf("%ld\n", table->nCol);
table->col = 0;
table->col = (long long*) malloc(table->nCol);
fread(table->row, sizeof(long long), table->nRow, prova1);
fread(table->col, sizeof(long long), table->nCol, prova2);
int res = calcLcs(table->row,table->nRow,table->nCol,table->col);
printf("%d",res);
/*
int vet[40];
n=fread(vet,sizeof(int),40,prova1);
for(i=0;i<40;i++) printf("%d ", vet[i]);
printf("%d",n);
fclose(prova2);
*/
FILE *out = fopen(output, "w");
printf((const char *) out, "%d\n", res);
fclose(prova1);
fclose(prova2);
fclose(out);
return res;
}
//this is main.c
#include <stdio.h>
#include "extlcs.h"
int main(int argc, char** argv) {
if(argc!=4){
printf("errore");
return -1;
}
extlcs(argv[1],argv[2],argv[3]);
return 0;
}
I'm trying to write a code that take two files and compare them with the lcs algoritm. i can't understand why the program give me segmentation fault
33 Views Asked by Andrea At
1
I suspect
malloc(table->nRow).It looks too small, only space for nRow bytes, but needs space for nRow
long longas far as I can tell.Similar for
malloc(table->nCol).You probably want to multiply by
sizeof(long long).And better look up some best practices on malloc. (E.g. not repeating types and not casting.)