Gacu07
Gacu07

Reputation: 21

Leaked memory,segmentation fault,C

gcc shows 0 errors, but valgrind shows that memory leaks and I cant execute my program because segmentation fault (core dumped) any suggestions? I checked allocation alone and its fine valgrind shows 0 memory leaked.There is a problem somewhere in file operations but I cant find it.

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

int* arrsize(FILE *plik)
{
if (plik == NULL) {
    printf("Error: file pointer is null.");
    return 0;
}
int* size;
fscanf(plik, "%d", &size);
return size;
}


int main()
{
int i = 0, j = 0, k = 0, a = 0;

FILE *fp;
if ((fp = fopen("matrix.txt", "r")) == NULL)
{
    printf("Error: file pointer is null.\n");
    return 1;
}
int size = arrsize(fp);

printf("Array size is %d x %d   ", size, size);



double **arr = (double **)malloc(size * sizeof(double *));
for (i; i < size; i++)
    arr[i] = (double *)malloc(size * sizeof(double));


for (j; j < size; j++) {
    fscanf(fp, "%d", &arr[i][j]);
}



for (i; i < size; i++)
{
    for (j = 0; j < size; j++)
    {

        printf("%lf\n", &arr[i][j]);
    }
}

for (k; k < size; k++) {
    free(arr[k]);
}
free(arr);

fclose(fp);

return 0;
}

Upvotes: 1

Views: 209

Answers (1)

patrickmdnet
patrickmdnet

Reputation: 3392

Change arrsize to actually return an int, not an int*:

int arrsize(FILE *plik)
{
    if (plik == NULL) {
        printf("Error: file pointer is null.");
        return 0;
    }
    int size;
    fscanf(plik, "%d", &size);
    return size;
}

Upvotes: 3

Related Questions