分段错误(核心转储)用C错误 [英] Segmentation fault (core dumped) error in C

查看:189
本文介绍了分段错误(核心转储)用C错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个C程序进行总结和。减去两个复数。
这里的code:

I am trying to write a C program to sum and substract two complex numbers. Here's the code:

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

typedef struct cplx
{
    int re;
    int im;
} cplx;

cplx* sum(cplx *x, cplx *y,int n)
{
    cplx *z; int i;
    for(i=0;i<n;i++)
    {
    z[i].re=x[i].re+y[i].re;
    z[i].im=x[i].im+y[i].im;
    }
    return z;
}

cplx* difference(cplx *x, cplx *y, int n)
{
    cplx *z; int i;
    for(i=0;i<n;i++)
    {
    z[i].re=x[i].re-y[i].re;
    z[i].im=x[i].im-y[i].im;
    }
    return z;
}

cplx* sumdiff(cplx *x,cplx *y, int n,cplx* (*op)())
{
    return(op(x,y,n));
}

int main(void)
{
    cplx *z1,*z2,*s,*diff;
    int m,n,i;
    printf("Give the number of complex numbers to add and substract:");
    scanf("%d",&n);
    z1=(cplx*)malloc(n*sizeof(cplx));
    z2=(cplx*)malloc(n*sizeof(cplx));
    s=(cplx*)malloc(n*sizeof(cplx));
    diff=(cplx*)malloc(n*sizeof(cplx));
    if ( z1==NULL || z2==NULL || s==NULL || diff==NULL)
    {
        printf("Allocation failed.\nEnding program.");
        exit(0);
    }
    printf("Give the numbers of the first vector:\n");
    for(i=0;i<n;i++)
    {
        printf("Re(z1[%d])=",i+1); scanf("%d",&m);
        z1[i].re=m;
        printf("Im(z1[%d])=",i+1); scanf("%d",&(z1[i].im));
    }
    printf("Give the numbers of the second vector:\n");
    for(i=0;i<n;i++)
    {
        printf("Re(z2[%d])=",i+1); scanf("%d",&(z2[i].re));
        printf("Im(z2[%d])=",i+1); scanf("%d",&(z2[i].im));
    }
    s=sum(z1,z2,n);
    diff=difference(z1,z2,n);
    s=sumdiff(z1,z2,n,sum);
    diff=sumdiff(z1,z2,n,difference);
    for(i=0;i<n;i++)
    {
        printf("z1[%d]+z2[%d]=%d+j(%d)\nz1[%d]+z2[%d]=%d+j(%d)\n",i+1,i+1,s[i+1].re,s[i+1].im,i,i,diff[i+1].re,diff[i+1].im);
    }
    free(z1); free(z2); free(s); free(diff);
return 0;
}

它编译罚款与海湾合作委员会,但是当我运行它,在执行前S = SUM(Z1,Z2,N)停止;段故障(核心转储)。
我在做什么错了?

It compiles fine with GCC but when I run it, the execution stops before s=sum(z1,z2,n); with a segmentation fault (core dumped). What am I doing wrong ?

推荐答案

以Z 区别是一个未初始化的指针。你得到了一个未定义的行为(可能崩溃)当您尝试写这个。你需要在每一项功能以Z 分配内存。

z in sum and difference is an uninitialised pointer. You get undefined behaviour (and likely a crash) when you try to write to this. You need to allocate memory for z in each of these functions.

cplx* sum(cplx *x, cplx *y,int n)
{
    cplx *z = malloc(n * sizeof(*z));
    int i;
    if (z == NULL) {
        return NULL;
    }

您还必须确保你免费内存从这些函数返回。在code

You'll also have to make sure you free the memory returned from these functions. The code

s=sum(z1,z2,n);
diff=difference(z1,z2,n);
s=sumdiff(z1,z2,n,sum);
diff=sumdiff(z1,z2,n,difference);

目前就这两个泄漏 S的第一个实例差异

这篇关于分段错误(核心转储)用C错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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