Home > database >  Why I am getting segmentation fault when trying to run the find function even though accessing memor
Why I am getting segmentation fault when trying to run the find function even though accessing memor

Time:12-28

Find function is not working in the program. I think it is because of segmentation fault as my compiler is showing, but I am not able to understand why? Because I used memory properly. If it is not because of segmentation fault, then why I am not getting my desired output, even though I am not getting any error.

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

void find(int **p) {
    int small,large,i,j;
    small=large=p[i][j];
    for(i=0; i<3; i  ) {
        for(j=0; j<3; j  ) {
            if(small>p[i][j])
                small=p[i][j];
            else if(large<p[i][j])
                large=p[i][j];
        }
    }
    printf("\nSmallest : %d\nLargest : %d",small,large);
}

int main() {
    int **p;
    p=(int **)malloc(sizeof(int)*3);
    if(p==NULL) {
        printf("Unable to allocate memory.");
        exit(1);
    }
    int i;
    for(i=0; i<3; i  ) {
        *(p i)=(int *)malloc(sizeof(int)*3);
    }
    int j;
    for(i=0; i<3; i  ) {
        for(j=0; j<3; j  )
            scanf("%d",(*(p i) j));
    }
    for(i=0; i<3; i  ) {
        for(j=0; j<3; j  )
            printf("\nValue of [%d][%d] : %d",i,j,*(*(p i) j));
    }
    find(p);
    free(p);
    return 0;
}

CodePudding user response:

There is a typo

p=(int **)malloc(sizeof(int)*3);
                        ^^^   

It seems you mean

p=(int **)malloc(sizeof(int *)*3);
                        ^^^^^

Apart from this memory freeing

free(p);

you need also to free each allocated array as for example

for ( i = 0; i < 3; i   )
{
    free( *( p   i ) );
}

free( p );

Within the function find you are using uninitialized variables i and j.

void find(int **p) {
    int small,large,i,j;
    small=large=p[i][j];
    //...

You need to initialize them

void find(int **p) {
    int small,large,i = 0,j = 0;
    small=large=p[i][j];
    //...

Though it would be simpler to write at least like

void find(int **p) {
    int small = p[0][0], large = p[0][0];

    for ( int i = 0; i < 3; i   )
    //...
  • Related