Getting segmentation fault while using malloc

两盒软妹~` 提交于 2019-12-11 01:37:41

问题


I asked my problem here The largest size of 2-D array in C and what I got answer there before declaration as duplicate by some people, I modified my code like this:

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

int main()
{
    int i,j,n,m,p = 0 ;
    int sum[100000] = {0};

    scanf("%d%d%d",&n,&m,&p);

    /*for ( i = 0 ; i < n ; i++ )
    {
        for( j = 0 ; j < m ; j++ )
        {
            a[i][j] = j + 1 ;
        }
    }*/
    int **a = (int **) malloc(sizeof(int)*n);
    for(i=0; i<n; i++)
    {
        a[i] = (int *) malloc(sizeof(int)*m); 

       for(i=0; i<n; i++){
           for(j=0; j<m; j++){
            a[i][j] = j + 1 ;

           }
       }

    }
    return 0;
}

But still I am getting the same segmentation fault.Please help me to fix it and I hope this question will not be declared as duplicate. :P


回答1:


You're telling malloc() the wrong size.

This:

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

should be:

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

Don't cast the result of malloc(), and use sizeof on the type the return pointer points at, i.e. int * which probably has a different size than int on your system.

Thus, thus:

a[i] = (int *) malloc(sizeof(int)*m); 

should be:

a[i] = malloc(m * sizeof *a[i]);

Add code to make sure all malloc() succeed, i.e. never return NULL, before relying on the pointers being valid. Also make sure the initial scanf() returns 3, and print out the values of n, m and p. Also remove sum.




回答2:


int **a = (int **) malloc(sizeof(int)*n); is wrong. What you want here is an array of pointer, so you should do int **a = (int **) malloc(sizeof(int *)*n); instead.



来源:https://stackoverflow.com/questions/23474293/getting-segmentation-fault-while-using-malloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!