Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault at the end of the C program

Tags:

c

Is the segmentation fault at the end of the code (just to allocate memory to 2D array and print the result)? The last printf statement is being printed and any code that I add at the end runs successfully and then segfault appears.

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

int main(void)
{
    int n,i,j,**mat;

    printf("\nEnter the size of the square matrix: ");
    scanf("%d",&n);

    *mat = (int **)malloc(n*sizeof(int *)); 

    for(i=0;i<n;i++)
    {
      mat[i]= (int *)malloc(n*sizeof(int));
    }

    for(i=0;i<n;i++)
    {
      for(j=0;j<n;j++) printf("%d\t",mat[i][j]=rand()%10*i+j);
      printf("\n\n\n");
    }

    printf("Bye\n");
    return 0;
}

Technically *mat in 8th line (printed in code) should be mat, but then everything is fine. The code mentioned compiles (with obvious warning of incompatible pointer type in gcc) and works except at the end when it prints segfault. Had there been a segfault in the program, it wouldn't had run till the end!

like image 466
man_stack Avatar asked Oct 31 '25 12:10

man_stack


1 Answers

*mat = (int **)malloc(n*sizeof(int *));

should be

mat = (int **)malloc(n*sizeof(int *)); 

Unless I change the line to this, the program segfaults right there. Through sheer luck and undefined behaviour your program manages to run for a little longer.

Also there is no need to cast the return value of malloc. Here are a couple reasons why you probably shoudn't.

like image 167
Alexguitar Avatar answered Nov 02 '25 03:11

Alexguitar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!