获取分段错误而使用malloc [英] Getting segmentation fault while using malloc

查看:195
本文介绍了获取分段错误而使用malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问我的问题就在这里 2-最大规模用C 二维数组和我得到了什么声明为重复一些人回答之前那里,我修改了code是这样的:

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;
}

不过还是我收到相同的分段fault.Please帮我解决它,我希望这个问题将不会被宣布为重复。 :P

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

推荐答案

您是说的malloc()错误的大小。

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

应该是:

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

不要投的结果的malloc() ,并使用的sizeof 的类型的返回指针点,即为int * 这可能有不同的尺寸比 INT 您的系统上。

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.

因此​​,这样的:

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

应该是:

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

添加code,以确保所有的malloc()成功,也就是有去无回 NULL ,依靠前在指针是有效的。另外,还要确保初始 scanf()的收益 3 ,并打印出的n的值 M p 。同时删除

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.

这篇关于获取分段错误而使用malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆