Segmentation fault at the end of the C program

时间:2015-12-14 18:03:50

标签: 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!

3 个答案:

答案 0 :(得分:4)

*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.

答案 1 :(得分:3)

要实际回答您的问题,您在main()函数结束后得到分段错误的原因是堆栈已损坏。

stack pointer已被覆盖,这意味着当main()尝试返回时,堆栈指针包含无效值。这会导致程序尝试从进程的地址空间外部访问内存。如果您使用exit(0),则可能完全避免分段错误。

请记住,您的程序会导致未定义的行为。有时你会在最后得到一个分段错误,有时在执行期间,有时根本不会(并且可能发生各种其他奇怪的事情)。

答案 2 :(得分:1)

*mat = (int **)malloc(n*sizeof(int *));取消引用未分配的指针。这会导致未定义的行为 ...

未定义意味着任何事情都可能发生。阅读this.在您的计划结束之前,您可能无法看到错误解除分配的结果。

进一步说明,you should not cast the result of malloc。以下内容:

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

需要替换为:

mat = malloc(n * sizeof mat*);

随着对其余内存分配行的一些修改。